使用 javascript 将反斜杠转换为正斜杠无法正常工作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6417641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting backslashes into forward slashes using javascript does not work properly?
提问by Junior Mayhé
I have a javascript variable comming from legacy system with backslashes into forward slashes:
我有一个来自旧系统的 javascript 变量,带有反斜杠到正斜杠:
'/46\465531_Thumbnail.jpg'
'/46\465531_Thumbnail.jpg'
and I am trying to convert into this:
我正在尝试转换为:
'/46/465531_Thumbnail.jpg'
.
'/46/465531_Thumbnail.jpg'
.
There is no way to fix the problem on the legacy system.
没有办法解决遗留系统上的问题。
Here is the command I am running on IE8 browser:
这是我在 IE8 浏览器上运行的命令:
javascript:alert("/465531_Thumbnail.jpg".replace(/\/g,"/"));
as response I get:
作为回应,我得到:
---------------------------
Message from webpage
---------------------------
/46&5531_Thumbnail.jpg
---------------------------
OK
---------------------------
actually I just want to be translated as '/46/465531_Thumbnail.jpg'
其实我只是想被翻译成 '/46/465531_Thumbnail.jpg'
What is wrong?
怎么了?
回答by Pointy
You need to double the backslash in your string constant:
您需要将字符串常量中的反斜杠加倍:
alert("/46\465531_Thumbnail.jpg".replace(/\/g,"/"));
If your legacy system is actually creating JavaScript string constants on your pages with embedded, un-quoted (that is, not doubled) backslashes like that, then it's broken and you'll have problems. However, if you're getting the strings via some sort of ajax call in XML or JSON or whatever, then your code looks OK.
如果您的旧系统实际上是在您的页面上创建带有嵌入的、未加引号(即,不是双倍)反斜杠的 JavaScript 字符串常量,那么它就坏了,您就会遇到问题。但是,如果您通过 XML 或 JSON 或其他形式的某种 ajax 调用获取字符串,那么您的代码看起来没问题。
回答by mellamokb
It is actually interpreting \46
as an escape-code sequence for the character &
. If you are going to hard-code the string, you need to escape the \
:
它实际上解释\46
为字符的转义码序列&
。如果要对字符串进行硬编码,则需要转义\
:
alert("/46\465531_Thumbnail.jpg".replace(/\/g,"/"));
^^ change \ to \
Sample: http://jsfiddle.net/6QWE9/
回答by RHSeeger
The replacement part isn't the problem, it's the string itself. Your string:
替换部分不是问题,而是字符串本身。你的字符串:
"/465531_Thumbnail.jpg"
isn't /46\465531
. Rather, the backslash is acting as an escape character. You need to change it to:
不是/46\465531
。相反,反斜杠充当转义字符。您需要将其更改为:
javascript:alert("/46\465531_Thumbnail.jpg".replace(/\/g,"/"));
ie, escapeing the backslash with a backslash.
即,用反斜杠转义反斜杠。
回答by Jon
Nothing wrong with the replace. The input is wrong.
替换没有错。输入错误。
javascript:alert("/46\465531_Thumbnail.jpg".replace(/\/g,"/"));
^
\---------------- need to escape this!