views:

45

answers:

5

Hello,

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!

+1  A: 

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"; });
Nick Craver
+1  A: 

\\$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.

bobince
Creating the new RegExp is slower than having the reg exp already defined. Not huge, but could be noticeable if there is a large list of things to replace and total milliseconds count.
epascarello
A: 

THAT'S IT bobince!! Thank you very much, it works as we expected! :-)

Arturo
You do not thank in the answers, you thank in comments of the answer. You also mark the answer as correct.
epascarello
A: 

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]; });
Gumbo
A: 

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");
epascarello