I am trying to replace the backslash (escape) character in a Javascript string literal.
I need to replace it with a double backslash so that I can then do a redirect:
var newpath = 'file:///C:\funstuff\buildtools\viewer.html'.replace(/\\/g,"\\");
window.location = newpath;
However, it seems to have no result.
I don't have the option of properly escaping the backslashes before they are handled by Javascript.
How can I replace (\) with (\\) so that Javascript will be happy?
Thanks, Derek
The escape() function is deprecated. Use encodeURI() or encodeURIComponent() instead.
String literal syntaxUse the escape sequence \n to represent a new-line character as part of the string. Use the escape sequence \\ to represent a backslash character as part of the string. You can represent a single quotation mark symbol either by itself or with the escape sequence \' .
Javascript uses '\' (backslash) in front as an escape character. To print quotes, using escape characters we have two options: For single quotes: \' (backslash followed by single quote) For double quotes: \” (backslash followed by double quotes)
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';
You should be replacing with "\\\\" because "\\" is escaping into a single \ thus no change.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With