Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex and JavaScript String With a Dollar ($) at the end

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?

like image 264
James Wiseman Avatar asked May 26 '26 13:05

James Wiseman


2 Answers

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.

like image 119
Pointy Avatar answered May 28 '26 03:05

Pointy


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, " "));
like image 41
Tobias Cohen Avatar answered May 28 '26 01:05

Tobias Cohen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!