0

I have this URL :

http://example.com/example/sample/example.jpg

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.

2
  • Try .replace(/\//g,'\\/') Commented Sep 10, 2014 at 8:21
  • Test: '\/' === '/' Commented Sep 10, 2014 at 8:45

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You also need the regex /\//g to match all slashes, not just the first.
1

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

1

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('\\/');
}

Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.