19

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

1
  • If you store the backslash in HTML you can use .replace(/\\/g,"\\\\"); with it. e.g if there is a backslash in the HTML document, then you can go document.body.innerHTML.replace(/\\/g, "\\\\");, which will replace all backslashes with a double backslash.
    – Viliami
    Nov 30, 2016 at 21:59

4 Answers 4

24

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';
3
  • 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="hunlock.com/blogs/… Complete Javascript Strings Reference</a>
    – dbasch
    Sep 4, 2009 at 0:59
  • I read through this but I still don't see why this difference exists: hunlock.com/blogs/The_Complete_Javascript_Strings_Reference Sorry, I'm a Stack Overflow n00b ;)
    – dbasch
    Sep 4, 2009 at 1:00
  • @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
    Sep 4, 2009 at 7:16
4

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

0
3

To better demonstrate and understand the string-escaping behavior, take the following example:

You can see what the string looks like in memory after being parsed by the JS-engine by splitting the string, thus also offering potential (ugly) solutions around this issue:

'file:///C:\funstuff\buildtools\viewer.html'.split('')
//>
 ["f", "i", "l", "e", ":", "/", "/", "/", "C", ":", "", "u", "n", "s", "t", "u",
  "f", "f", "", "u", "i", "l", "d", "t", "o", "o", "l", "s", "", "i", "e", "w",
  "e", "r", ".", "h", "t", "m", "l"]

'file:///C:\funstuff\buildtools\viewer.html'.split('').map( function(e){
     return e.charCodeAt()
});
//>
[102, 105, 108, 101, 58, 47, 47, 47, 67, 58, 12, 117, 110, 115, 116, 117, 102,
 102, 8, 117, 105, 108, 100, 116, 111, 111, 108, 115, 11, 105, 101, 119, 101, 
 114, 46, 104, 116, 109, 108]
//>in Hex values by applying .toString(16)
["66", "69", "6c", "65", "3a", "2f", "2f", "2f", "43", "3a", "c", "75", "6e", 
 "73", "74", "75", "66", "66", "8", "75", "69", "6c", "64", "74", "6f", "6f", 
 "6c", "73", "b", "69", "65", "77", "65", "72", "2e", "68", "74", "6d", "6c"]

Basically the single backslash escapes the following character, thus giving rise to unexpected results, if the escaping-context is not heeded.

Solution:

Through a look-up-table, you can restore many errantly escaped characters if they lie outside the printable ASCII character range of \x20-\x7F. For the example above for instance, 12 or \x0c [ 12..toString(16) ] would become '\\'+'v', and so on.

PS: Be aware that a loss of information occured, and you are trying to restore information through contextual- or meta- information, meaning in your case that the string is in the printable ASCII range.

Please share any implementations with the community. Cheers!

-7

<< Escape Characters Replacement>>

import java.util.Scanner;

public class Example7 {

  public static void main(String[] args) {
    Scanner in=new Scanner(System.in);
    System.out.println("Please enter a sentence: ");
    String a=in.nextLine();
    //System.out.println("the word had enter: "+a);

    String Str1 = a.replace("\\n", "(new_line)");
    //System.out.println(Str1);
    String Str2 = Str1.replace("\\t", "(tab)");
    //System.out.println(Str2);
    String Str3 = Str2.replace("\\t", "(tab)");
    String Str4 = Str3.replace("\\\\", "(comment_line)");
    String Str5 = Str4.replace(":)", "(smile) ");
    System.out.println("The new sentence:"  +Str5);
  }
}

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.