views:

276

answers:

3

here is my string:

var str = "This is my \string";

This is my code:

var replaced = str.replace("/\\/", "\\\\");

I can't get my output to be:

"This is my \\string"

I have tried every combination I can think of for the regular expression and the replacement value.

Any help is appreciated!

+1  A: 

The string doesn't contain a backslash, it contains the \s escape sequence.

var str = "This is my \\string";

And if you want a regular expression, you should have a regular expression, not a string.

var replaced = str.replace(/\\/, "\\\\");
David Dorward
+1  A: 

The problem is that the \ in your first line isn't even recognized. It thinks the backslash is going to mark an escape sequence, but \s isn't an escape character, so it's ignored. Your var str is interpreted as just "This is my string". Try str.indexOf("\\") - you'll find it's -1, since there is no backslash at all. If you control the content of str, do what David says - add another \ to escape the first.

Tesserex
The problem is that I don't control the value. Its actual a windows path that I'm dealing with ( \wp-content\photos\image123.jpg ). The string is given to me as "\wp-content\photos\image123.jpg" but I can't do anything with it because the backslashes disapear. I understand they are being parsed as escape characters but I don't know how to fix it.
Frankie
Either you are getting broken JS (in which case you can't fix it) or you are getting a string in some other language and outputting it to JS without escaping special characters first, in which case you have to fix it there.
David Dorward
Agreed - the only way escape sequences can get into a string is if the string is constructed in javascript. If it's coming from a form field, ajax response, query string, etc, it shouldn't need escaping. When you say "the string is given to me as..." - HOW is it actually provided to you?
Graza
A: 

I haven't tried this, but the following should work

var replaced = str.replace((new RegExp("\s"),"\\s");

Essentially you don't want to replace "\", you want to replace the character represented by the "\s" escape sequence.

Unfortunately you're going to need to do this for every letter of the alphabet, every number, symbol, etc in order to cover all bases

Graza
`"\s"` is `"s"`, so this will get any other s characters too. You'd end up prefixing every character in the string with a `\` unless the sequence was a control character.
David Dorward