Javascript – Replacing the escape character in a string literal

If it’s a literal, you need to escape the backslashes before Javascript sees them; there’s no way around that.

var newpath="file:///C:\\funstuff\\buildtools\\viewer.html";
window.location = newpath;

If newpath is getting its value from somewhere else, and really does contain single backslashes, you don’t need to double them up; but if you really wanted to for some reason, don’t forget to escape the backslashes in the replace() call:

newpath.replace(/\\/g,"\\\\");

Why do you not have the option of properly escaping the backslashes before they are handled by Javascript? If the problem is that your Javascript source is being generated from some other scripting language that itself uses \ as an escape character, just add a level of escaping:

var newpath="file:///C:\\\\funstuff\\\\buildtools\\\\viewer.html";

Leave a Comment