3

I am using this expression: /\W+/g to match all characters that are not numbers, letters and spaces. It seems to be including spaces. How would I build a regex that did not include spaces?

3 Answers 3

2
/[^a-z0-9\s]+/ig

Explanation:

[^   Character class which matches characters NOT in the following class
a-z  All lowercase letters of the alphabet
0-9  All numbers
\s   Whitespace characters
]    End of the character class

i   Case-insensitivity to match uppercase letters
Sign up to request clarification or add additional context in comments.

5 Comments

thanks, my guess is that I was not clear enough in my question, but all I needed to add to yours was \s so what I found to work was /[^a-z0-9\s]+/ig
This regex still matches spaces, I think you want something like /[^a-z0-9\s]+/ig
@chromedude: I'm glad it's working for you. Fixed answer for clarity.
@Tim Cooper - the regex still does not match spaces!
However, this works: /[^0-9a-zA-Z]/g as per this post: stackoverflow.com/a/24062304/3062486
2

A more accurate wording for \W is any Non-Alphanumeric character. \s is for Any Whitespace.

So, it would be something like this: [^\s]

Comments

0

\W means "non-word characters", the inverse of \w, so it will match spaces as well. I'm a bit surprised it doesn't match numbers, though.

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.