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

查看:226
本文介绍了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:\funstuff\buildtools\viewer.html'.replace(/\\/g,"\\");
window.location = newpath;

但是,似乎没有结果。

However, it seems to have no result.

在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?

谢谢
Derek

Thanks, Derek

推荐答案

如果这是一个文字,你需要在 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天全站免登陆