user4207046
user4207046

Reputation:

Js replace slashes in string

I have url that i need to change to a valid slashes.

var url = data\14/loto/posts.json

I need this to change to this:

data/14/loto/posts.json

But this is not working:

url.replace('\', '/');

Upvotes: 0

Views: 640

Answers (2)

nicael
nicael

Reputation: 18995

Should be

var url = "data\\14/loto/posts.json" // "\\" is because slash should be escaped, otherwise your url isn't a valid string
url = url.replace(/\\/g, '/');

Upvotes: 1

Jackson Ray Hamilton
Jackson Ray Hamilton

Reputation: 9466

In JS, you need to escape backslashes, because they are normally escape characters themselves.

url.replace('\\', '/');

Additionally, if you want to escape multiple backslashes in the same string, use a regex literal with the g flag, "g" standing for "global".

url.replace(/\\/g, '/');

Upvotes: 1

Related Questions