8

I'm working in a javascript function, in a given string I need to replace // for only one slash / by now I have:

result= mystring.replace("\/\/", "/");

bt it's not working, I still get the string with double slash, so which is the proper regex to indicate the double slash to the replace function?

I already tried:

  • !//!
  • ////
  • ///g///g

Edit: I'm using it to correct a URL that is saved in the string, for example, sometimes that URL can be something like: mywebpage/someparameter//someotherparameter and that double slash gives problem, so I need to replace it to one single slash like: mywebpage/someparameter/someotherparameter

12
  • 1
    You need to provide a minimal reproducible example: Show how you define mystring. Show how you test the value of result. Commented Dec 17, 2016 at 18:49
  • why are you escaping it in a string? Commented Dec 17, 2016 at 18:49
  • "which is the proper regex" — Why are you asking about regex when you are using a string and not a regex? Commented Dec 17, 2016 at 18:50
  • 1
    "it's not working" Cannot reproduce Commented Dec 17, 2016 at 18:58
  • 1
    @SrednyMCasanova — Re edit: Don't just describe the strings, provide a minimal reproducible example Commented Dec 17, 2016 at 19:03

2 Answers 2

23

Use regex /\/\//(or /\/{2}/) with a global modifier to replace all occurrence.

result= mystring.replace(/\/\//g, "/");

console.log(
  'hi// hello//123//'.replace(/\/\//g, '/')
)

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

2 Comments

@SrednyMCasanova : glad to help :)
Take into account that the regex is not a string. I mean, "/\/\//g" does not work
6

There is no need to escape it if it is a string used as a replacement

console.log("asd//qwe".replace("//","/"));

If it were a regular expression, you would need to escape it

console.log("asd//qwe".replace(/\/\//,"/"));

Now if there is more than one set, than you need to use a regular expression with a global modifier.

console.log("asd//qwe".replace(/\/\//g,"/"));

Comments

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.