2

I want to replace the "/" into "\/" using javascript.

for example:

http://www.freeformatter.com/javascript-escape.html

to

http:\/\/www.freeformatter.com\/javascript-escape.html
1
  • In what context are you using this? Are you trying to manually escape JavaScript strings? Commented Sep 3, 2015 at 21:15

3 Answers 3

2

You can do:

str.replace(/\//g, "\\/");

where str is the variable that holds the string value.

Demo: http://jsbin.com/zijaqo/1/edit?js,console

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

Comments

1

use replace:

"http:/www.freeformatter.com/javascript-escape.html".replace(/\//g, "\\/");

If you have the string in a variable:

var url = "http:/www.freeformatter.com/javascript-escape.html";
url.replace(/\//g, "\\/");

1 Comment

right now, this outputs "http:\\/www.freeformatter.com\\/javascript-escape.html" instead of "http:\/\/www.freeformatter.com\/javascript-escape.html". What i need to get "http:\/\/www.freeformatter.com\/javascript-escape.html".
0

You could use str.replace() and a Regular expression object here. Basically you just need to escape the escape character in your replacement string.

str = str.replace(new RegExp('/','g'),"\\/");

1 Comment

Consider expanding your answer to explain to the asker why this achieves the desired result, possibly linking to documentation. As is, this is only marginally useful.

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.