I have this URL :
I want to have this :
http:\ /\ /example.com\ /example\ /sample\ /example.jpg
I wrote this code :
function addslashes(str) {
return str.replace('/', '\/');
}
var url = http://example.com/example/sample/example.jpg
var t = addslashes(url);
alert(t);
As an alert, I still get the old URL. What's wrong with this code? Thanks.
3 Answers 3
If you want to print \ you must escape it with another backslash.
function addslashes(str) {
return str.replace(/\//g, '\\/');
}
Also, if you want the replace function to replace all occurrences, you must pass a regex with a g modifier instead of a string. If you pass a string it will only replace the first match and then end but with the modifier it will find all matches.
1 Comment
/\//g to match all slashes, not just the first.try this code fiddle:
function addslashes(str) {
return str.replace(/\//g, '\\/');
}
you need to add the g to set it to global, to replace all the '/' and in the replacing string you need to add '\'.
Comments
You have to add an additinal backslash to escape it right.
With replace you would only replace the first match. You can also use Regular expression as you can see on the other posts. But you can also use it with simple split and join functions
function addslashes(url) {
url.split('/').join('\\/');
}
.replace(/\//g,'\\/')'\/' === '/'