RedoColor
RedoColor

Reputation: 145

Replace string in JavaScript using regex

I am trying to replace a string (/\) in JavaScript with Forward slash (/).

For example, this: uploads/\images\cats\rr.jpg should become this: uploads/imagescats/rr.jpg

I tried string.replace(/\\/g,""); but is replacing only \ backslash.

And also, I tried replace \ with /

Anyone have an idea how I can replace this symbols? I don't understand regex very well.

Upvotes: 0

Views: 72

Answers (2)

user9274775
user9274775

Reputation:

If the rule is a "/\" or a "\" becomes "/", then use this regex: s = s.replace(/\/?\\/g, "/").

It looks for a backslash, optionally preceded by a forward slash, and replace it (or them) with a single forward slash.

const s = "uploads/\\images\\cats\\rr.jpg";
const res = s.replace(/\/?\\/g, "/");

console.log(res);

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 191058

You will need to include \/ in your regex and make it a charecter class.

string.replace(/[\\\/]/g,"");

Upvotes: 0

Related Questions