14

I have this string

we have two papers // two handbags /// three bags //// four bottles

I want it to become

we have two papers / two handbags / three bags / four bottles

I have tried string.replace(///g, '/') but it doesn't work

It returns a syntax error.

4 Answers 4

34

The answer is:

'one / two // three ///'.replace(/\/\/+/g, '/')

Let's go step by step to why it's correct.

First, to handle the error. It happened because the slash wasn't escaped. A regex begins with /, and to match all occurrences ends with /g, so to match all two slashes we would write:

/\/\//g
  1. begin regex - /
  2. match one slash - /
  3. match another slash - /
  4. all occurrences - /g

But then, given the input string above, the output would be:

one / two / three //

That is because /// matches two pairs of slashes, for each pair turns it into one and that's it. Regexes aren't iterative. So what we're looking for is to match two slashes or more, which will give the answer I wrote at the beginning.

Note that this would also work:

/\/+/g

However it will have bad performance, since it will match single slashes and will replace them with the same string.

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

1 Comment

But wouldn't /\/\/+/g match doubles of one or more?Why would it match a triplet, i.e. 3 slashes?
8

You should instead use :

"some string".replace(/\/+/g, '/')

+ means match one or more. / is used to delimit regex in its literal form. SO you've to escape it with a back slash.

2 Comments

right, your solution is more clean because there no need escape when delimit by quotes like this case
We don't want "one or more" in this example. We want "two or more"!
4

Your code doesnt work because you need escape the slash and add +, meaning it match every number of slashes

string.replace(/\/+/g, '\/') will work.

Comments

0
let txtNew = txtOrig.replace(/\/{2,}/g, "/");

This means 2 or more instances of slashes //, ///, etc. -> single /

I like this a bit more because the other ways can be confusing. I don't want to make it seem like I'm replacing a single slash, or that I'm replacing doubles only, even if in reality those methods work as intended.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.