Converting backslashes into forward slashes using

2019-01-15 06:43发布

I have a javascript variable comming from legacy system with backslashes into forward slashes:

'/46\465531_Thumbnail.jpg'

and I am trying to convert into this:

'/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:

javascript:alert("/46\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'

What is wrong?

4条回答
Melony?
2楼-- · 2019-01-15 07:21

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.

查看更多
我命由我不由天
3楼-- · 2019-01-15 07:35

Nothing wrong with the replace. The input is wrong.

javascript:alert("/46\\465531_Thumbnail.jpg".replace(/\\/g,"/"));
                     ^
                     \----------------  need to escape this!
查看更多
霸刀☆藐视天下
4楼-- · 2019-01-15 07:38

The replacement part isn't the problem, it's the string itself. Your string:

"/46\465531_Thumbnail.jpg"

isn't /46\465531. Rather, the backslash is acting as an escape character. You need to change it to:

javascript:alert("/46\\465531_Thumbnail.jpg".replace(/\\/g,"/"));

ie, escapeing the backslash with a backslash.

查看更多
劫难
5楼-- · 2019-01-15 07:41

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 \:

alert("/46\\465531_Thumbnail.jpg".replace(/\\/g,"/"));
          ^^ change \ to \\

Sample: http://jsfiddle.net/6QWE9/

查看更多
登录 后发表回答