Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting backslashes into forward slashes using javascript does not work properly?

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?

like image 479
Junior Mayhé Avatar asked Jun 20 '11 21:06

Junior Mayhé


People also ask

What is the difference between forward slashes and backslashes?

Summary: The Backslash and Forward SlashThe backslash (\) is mostly used in computing and isn't a punctuation mark. The forward slash (/) can be used in place of “or” in less formal writing. It's also used to write dates, fractions, abbreviations, and URLs.

How do you change a backslash with a forward slash?

Press \/ to change every backslash to a forward slash, in the current line. Press \\ to change every forward slash to a backslash, in the current line.

What does forward slash do in JavaScript?

This function will return a new string with the replaced string. A regular expression is used to replace all the forward slashes. As the forward slash (/) is special character in regular expressions, it has to be escaped with a backward slash (\).


1 Answers

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.

like image 93
Pointy Avatar answered Oct 18 '22 19:10

Pointy