I would like to remove spaces around hyphens in JS.
'Space - around - hypens'
=> 'Space-around-hypens'
I try the following, but it works only on the first hyphen:
str.replace(/s*-s*/, "-");
I also try this, but it throw an error that I don’t understand:
str.replaceAll(/s*-s*/, "-");
Uncaught TypeError: String.prototype.replaceAll called with a non-global RegExp argument
3
Answers
Use the /g flag in the regex to indicate that it should be applied globally throughout the string.
Originally, JavaScript didn’t have a
replaceAll
method, so to get the same effect asreplaceAll
through the replace method, we had to use regular expressions with it.Starting with ES12, you can use the
replaceAll
method added toString.prototype
.When using it with a
replaceAll
regular expression, you still need to always use theg
flag with it, otherwise you will get an error likeTypeError: String.prototype.replaceAll called with a non-global RegExp argument.