2

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?

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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, " "));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.