Reputation: 357
I'm Getting some images from API with Backward Slashes , and when I tried to display these images on my page its working fine on Chrome but on other browsers like FireFox and IE it's not working , after some googling I get to know that I have to pass URL with forward slashes , So I tried replacing it but it's not working ..
Following is the code that I tried...
Input
var test ="http:\\www.xyz.com\xy\ab\1324\1324.jpg";
var final = test.replace(/\\/g,"/");
Output
http:/www.xyz.comxyab13241324.jpg
Please Let me know where I'm going wrong , Thank you
Upvotes: 1
Views: 13770
Reputation: 2394
This is not possible — with the provided example-string or anything similar.
\x
is the first problem here. JavaScript thinks this is a Hexadecimal escape sequence, that's why the JavaScript-Interpreter is throwing an appropriate error:
Uncaught SyntaxError: Invalid hexadecimal escape sequence
And even if we take another example string: 'http:\\www.xyz.com\yy\ab\1324\1324.jpg'
it will fail.
JavaScript thinks that the backslashes are there to escape something as Octal escape sequence — that is why just entering this string into a JS-Console and hitting return gives you back:
"http:\www.xyz.comyyabZ4Z4.jpg"
To visualize it even more, enter into your console: 'http:\\www.xyz.com\yy\ab\1324\1324.jpg'.split('');
You'll see that even \132
gets converted to Z
.
I tried many things right now, like replacing/escaping, trying JSON.stringify, using a text-node, using CDATA inside a virtual XML-document, etc. etc. – nothing worked. If somebody finds a JavaScript-way for doing this, I'd be happy to know about it!
I don't know of any way for doing this inside JavaScript. There seems to be no chance.
Your only solution as I see it, is to escape it on the server-side.
In your case you will have to write a little server-script, that calls your used API and converts/escapes everything to be ready for your JS. And your JS calls this little server-script.
Upvotes: 1
Reputation: 8284
Taking a guess at piecing all of these things together:
var test ="http:\\www.xyz.com\xy\ab\1324\1324.jpg";
is not valid HTML.\
character, you have to escape it, so you would want var test = http:\\\\www.xyz.com
One way to check your work is to use JSON.stringify
to come up with the actual value that you need to type in your source code. E.g.:
var test = 'http:\\\\xyz.com';
console.log(test); // prints "http:\\xyz.com"
console.log(JSON.stringify(test)); // prints "http:\\\\xyz.com"
Upvotes: 0
Reputation: 386578
Its working fine with escaped backslashes.
var test ="http:\\\\www.xyz.com\\xy\\ab\\1324\\1324.jpg";
var final = test.replace(/\\/g,"/");
console.log(final);
Upvotes: 0