Replace multiple slashes in text with single slash with Javascript
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.
Your code doesnt work because you need escape the slash and add +
, meaning it match every number of slashes
string.replace(/\/+/g, '\/')
will work.
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
- begin regex - /
- match one slash - /
- match another slash - /
- 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.