Sheerwood John Caday
Sheerwood John Caday

Reputation: 229

how to replace the forward slash to backslash and forward slash using javascript

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

Upvotes: 2

Views: 3541

Answers (3)

Deftwun
Deftwun

Reputation: 1232

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'),"\\/");

Upvotes: 0

taxicala
taxicala

Reputation: 21759

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, "\\/");

Upvotes: 1

Cristian Lupascu
Cristian Lupascu

Reputation: 40516

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

Upvotes: 2

Related Questions