iNc0ming iNc0ming - 1 month ago 4
Javascript Question

Javascript replace unescaped slash

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


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


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?


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".


Ends up the same as:


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.