Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Replacing the escape character in a string literal

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

like image 333
dbasch Avatar asked Sep 03 '09 23:09

dbasch


People also ask

What can I use instead of escape in JavaScript?

The escape() function is deprecated. Use encodeURI() or encodeURIComponent() instead.

How do you escape a string literal?

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 \' .

How do you escape characters in a string JavaScript?

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)


2 Answers

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';
like image 173
moonshadow Avatar answered Sep 20 '22 17:09

moonshadow


You should be replacing with "\\\\" because "\\" is escaping into a single \ thus no change.

like image 43
McAden Avatar answered Sep 21 '22 17:09

McAden