Help with regular expressions (JS replace method)
We would like to do a replace in our string like this: - Every time a \n (new line) or \t (tab) or 开发者_开发问答\r (carriage return) appears, it should be replaced by the string "\n" or "\t" or "\r".
For example, this string:
"Hello, how are you? Fine thanks."Should be replaced by:
"Hello, how\n\tare you?\nFine thanks."Could you help us? We are trying with this code in Jscript (replace() method) but it doesn't work:
myString.replace(/([\n|\t])/g, "\\$1");
THANKS!
I'm not sure of an easy way to combine what you're doing, the long-hand will work though:
myString.replace(/\n/g, "\\n").replace(/\t/g, "\\t");
Or, you could do it in a single pass using a function, like this:
myString.replace(/([\n|\t])/g, function(a, m) { return m=="\n"?"\\n":"\\t"; });
\\$1
would be a backslash followed by the newline or tab. (Incidentally, [\n|\t]
is also not doing what you think. A character group doesn't need the |
.)
If you wanted to map string escapes, you could do it with an explicit RegExp
constructor:
var escapes= ['n', 't'];
for (var i= escapes.length; i-->0;)
s= s.replace(new RegExp('\\'+escapes[i], 'g'), '\\'+escapes[i]);
though it might not be worth it for just two escapes. But what about other control characters? And what about the backslash itself?
If you are trying to make a JavaScript string literal from a string, a better place to start might by JSON.stringify
.
I would use a an object that associates the characters to the escape sequences as a map as follows:
var map = {"\b":"\\b", "\t":"\\t", "\n":"\\n", "\v":"\\v", "\f":"\\f", "\r":"\\r"};
str = str.replace(/[\b\t\n\v\f\r]/g, function(val) { return map[val]; });
3 solutions:
var str = "";
for(var i=0;i<5000;i++){
str += "\t\n";
}
function replaceType( s ){
switch( s ){
case "\n":
return "\\n";
break;
case "\t":
return "\\t";
break;
default:
return s;
}
}
//slow solution
console.time("replace function");
str.replace(/([\n|\t])/g, replaceType);
console.timeEnd("replace function");
//fast solution
console.time("chained replace");
str.replace(/\t/g, "\\t").replace(/\n/g, "\\n");
console.timeEnd("chained replace");
//slightly slower than chained
var replaceChars = { "\\t": /\t/g, "\\n": /\n/g };
var out = str;
console.time("looped chained replace");
for(re in replaceChars){
out = out.replace(replaceChars[re], re);
}
console.timeEnd("looped chained replace");
精彩评论