Javascript - 替换字符串文字中的转义字符 [英] Javascript - Replacing the escape character in a string literal

查看:30
本文介绍了Javascript - 替换字符串文字中的转义字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试替换 Javascript 字符串文字中的反斜杠(转义)字符.

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:funstuffuildtoolsviewer.html'.replace(/\/g,"\");
window.location = newpath;

然而,似乎没有结果.

在反斜杠被 Javascript 处理之前,我无法正确转义它们.

I don't have the option of properly escaping the backslashes before they are handled by Javascript.

如何将 () 替换为 (\) 以使 Javascript 满意?

How can I replace () with (\) so that Javascript will be happy?

谢谢,德里克

推荐答案

如果是文字,你需要在 Javascript 看到它们之前转义反斜杠 ;没有办法解决这个问题.

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;

如果 newpath 从其他地方获取它的值,并且确实包含单个反斜杠,则不需要将它们加倍;但如果您出于某种原因真的想这样做,请不要忘记在 replace() 调用中转义反斜杠:

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,"\\");

为什么在反斜杠被 Javascript 处理之前,您没有正确转义反斜杠的选项?如果问题是您的 Javascript 源代码是由其他脚本语言生成的,而这些脚本语言本身使用 作为转义字符,只需添加一个转义级别:

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

这篇关于Javascript - 替换字符串文字中的转义字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆