Reputation:
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.
Upvotes: 14
Views: 16001
Reputation: 11974
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.
Upvotes: 0
Reputation: 2582
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
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.
Upvotes: 33
Reputation: 59232
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.
Upvotes: 8
Reputation:
Your code doesnt work because you need escape the slash and add +
, meaning it match every number of slashes
string.replace(/\/+/g, '\/')
will work.
Upvotes: 4