I'm trying to remove all ocurrences of dashes and underscores of a string with String.prototype.replace()
, but it's not working and I don't know why. My code:
var str = "dash-and_underscore";
str = str.replace(/_|\-/, " ");
console.log(str);
outputs:
"dash and_underscore"
in the Chrome console.
Since the |
acts like the OR
opperator, what am I doing wrong? I've tried the solution here, but it didn't work, or I'm too dumb to understand - which is an option ;)
Try this:
str = str.replace(/[_-]/g, " ");
[..]
defines a character classg
means global research
(You can write it with a quantifier /[_-]+/g
to remove several consecutive characters at a time.)
or
str = str.replace(/_|-/g, " ");
that is correct too, but slower. Note that the dash doesn't need to be escaped out of a character class since it isn't a special character.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With