0

I want to replace an unescaped slash in a string with backslash. But something weird happened:

"\content\hs\gj\home.css".replace(/\\/gi,"/")

which returns "contenthsgjhome.css". I understand that if change it to

"\\content\\hs\\gj\\home.css".replace(/\\/gi,"/")`

Then it will work as expected, but I can't change the string because it's just the output by nodejs path.join("conetnt", "hs", "gj", "home.css").

What I should do?

Jon Adams
  • 24,464
  • 18
  • 82
  • 120
iNc0ming
  • 383
  • 1
  • 6
  • 17
  • how do you actually get your string? Look at this SO article your string should not be possible if you don't produce it in javascript yourself: http://stackoverflow.com/questions/2479309/javascript-and-backslashes-replace – snies May 25 '12 at 06:37

2 Answers2

6

The reason it is returning "contenthsgjhome.css" is that your string doesn't really have any backslashes in it at all because single backslashes in a string literal will be ignored unless they make sense to escape the following character (e.g., "\\" or "\n"). "\c" has no special meaning as an escape so it is interpreted as "c".

"\content\hs\gj\home.css"

Ends up the same as:

"contenthsgjhome.css"

So there are no backslashes for .replace() to find.

(Note that if you do have escaped backslashes in a string literal like "\\" that is part of the literal syntax only and once interpreted the resulting string has only one backslash "\".)

Perhaps if you could explain what you mean by "it's just the output by FS" somebody could offer more advice. This is a common problem when JSP/ASP/PHP/etc outputs JS code - the escaping needs to happen in the JSP/ASP/PHP/etc code before the JS interpreter sees it.

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • 1
    Exactly, your string should be defined with doublslashes : `'\\content\\hs\\gj\\home.css'` – drinchev May 25 '12 at 06:35
  • thanks, the string is actually from the nodejs path.join("conetnt", "hs", "gj", "home.css") – iNc0ming May 25 '12 at 06:55
  • So it's in a variable, not in a string literal? Please update your question to show exactly how you use the output from `path.join("conetnt", "hs", "gj", "home.css")`. The example output in the [`path.join()` doco](http://nodejs.org/api/path.html#path_path_join_path1_path2) seems to be joining with forward slashes, not backslashes. If you're running code under nodejs that produces output sent to the browser you need to do the escaping directly in the nodejs code, not in the browser. – nnnnnn May 25 '12 at 06:59
  • nnnnnn, thanks for your advice. I solve it by using ["conetnt", "hs", "gj", "home.css"].join("/") instead. Problem solved now! – iNc0ming May 25 '12 at 11:37
0
yourstring.split(String.fromCharCode(92)).join('/')
user2939415
  • 864
  • 1
  • 11
  • 22