iNc0ming
iNc0ming

Reputation: 383

Javascript replace unescaped slash

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?

Upvotes: 0

Views: 2545

Answers (2)

user2939415
user2939415

Reputation: 894

yourstring.split(String.fromCharCode(92)).join('/')

Upvotes: 0

nnnnnn
nnnnnn

Reputation: 150080

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.

Upvotes: 6

Related Questions