views:

2847

answers:

2

Hi everyone,

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

+3  A: 

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';
moonshadow
Great answer moonshadow.I can not change the path prior to Javascript seeing it, because it is interpolated into the Javascript by an ANT copy and filter task. I am going to have to put in a change request for the ANT task.Can you explain why it is impossible to replace the escape character in a string literal but it is possible in a string object?I read through this but I still don't see why this difference exists:<a href="http://www.hunlock.com/blogs/The_Complete_Javascript_Strings_Reference">The Complete Javascript Strings Reference</a>
dbasch
I read through this but I still don't see why this difference exists:http://www.hunlock.com/blogs/The_Complete_Javascript_Strings_ReferenceSorry, I'm a Stack Overflow n00b ;)
dbasch
@dbasch: Your example code can't replace the '\' characters because the characters no longer exist in the string by the time the replace() runs. They are escape characters: characters that control the parsing of the string literal and are consumed in the process.
moonshadow
Ahhhh. I see. Thanks.
dbasch
+2  A: 

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

McAden
I tried this and it did not make the replacement.
dbasch