In answering this PHP question: regex - preg_replace string, I came across something in Javascript I didn't understand. Given the following:
var s = "abc1!?d$";
alert(s.replace(/\W+/, " "));
I am alerted:
abc d$
Why is it not stripping out the last dollar?
Because there's an intervening word character. Try this:
alert(s.replace(/\W+/g, ' '));
Without the "g" suffix on the regex, it only makes one substitution. That handles the "!?" in the middle, but that "d" ends the sequence.
Because you're not using the (g)lobal flag on your matcher, so it's only matching the first consecutive sequence of non-word characters.
The following should give the result you expect:
var s = "abc1!?d$";
alert(s.replace(/\W+/g, " "));
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