0

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.

4
  • You need to include the escaped forward slash in the regex. s.replace(/\/\\/g, "/") Keep in mind that the first and last / are just delimiters that indicate the start and end of the regex grammar. Commented Feb 6, 2018 at 18:26
  • ...I assume it's the sequence of "/\" that you're trying to replace. Commented Feb 6, 2018 at 18:27
  • this is my string uploads/\images\cats\rr.jpg and i wanna receive this uploads/images/cats/rr.jpg Commented Feb 6, 2018 at 18:29
  • 1
    If the rule is a "/\" or a "\" becomes "/", then s = s.replace(/\/?\\/g, "/") Commented Feb 6, 2018 at 18:32

2 Answers 2

1

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);

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

Comments

0

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

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

1 Comment

thanks, works, but i receive uploads//images/cats/rr.jpg. so i use this instead s.replace(/\/?\\/g, "/") -- thanks to Skinny Pete

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.