Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
58
rated 0 times [  62] [ 4]  / answers: 1 / hits: 91084  / 15 Years ago, thu, september 3, 2009, 12:00:00

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:funstuffbuildtoolsviewer.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


More From » string

 Answers
16

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';

[#98760] Tuesday, September 1, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gabriel

Total Points: 323
Total Questions: 107
Total Answers: 108

Location: Federated States of Micronesia
Member since Sun, May 16, 2021
3 Years ago
gabriel questions
Sun, Feb 14, 21, 00:00, 3 Years ago
Tue, Dec 8, 20, 00:00, 4 Years ago
Mon, Jun 8, 20, 00:00, 4 Years ago
Tue, May 19, 20, 00:00, 4 Years ago
;