Javascript - Replacing the escape character in a string literal

前端 未结 4 624
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-03 05:38

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 redirec

4条回答
  •  不知归路
    2020-12-03 06:06

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

提交回复
热议问题