I am searching for a regular expression for allowing alphanumeric characters, -, _ or spaces in JavaScript/jQuery. I tried Googling but wasn't able to find that.
Can anyone help me out with this?
Thanks in advance.
Alphanumeric characters by definition only comprise the letters A to Z and the digits 0 to 9. Spaces and underscores are usually considered punctuation characters, so no, they shouldn't be allowed. If a field specifically says "alphanumeric characters, space and underscore", then they're included.
The regex \w is equivalent to [A-Za-z0-9_] , matches alphanumeric characters and underscore.
The most common forms of whitespace you will use with regular expressions are the space (␣), the tab (\t), the new line (\n) and the carriage return (\r) (useful in Windows environments), and these special characters match each of their respective whitespaces.
Yes, also your regex will match if there are just spaces. My reply was to Neha choudary's comment. @Pierre Three years later -- I came across this question today, saw your comment; I use regex hero (regexhero.net) for testing regular expressions.
Character sets will help out a ton here. You want to create a matching set for the characters that you want to validate:
\w
, which is the same as [A-Za-z0-9_]
in JavaScript (other languages can differ).-
and spaces, which can be combined into a matching set such as [\w\- ]
. However, you may want to consider using \s
instead of just the space character (\s
also matches tabs, and other forms of whitespace) -
as \-
so that the regex engine doesn't confuse it with a character range like A-Z
^
and $
The full regex you're probably looking for is:
/^[\w\-\s]+$/
(Note that the +
indicates that there must be at least one character for it to match; use a *
instead, if a zero-length string is also ok)
Finally, http://www.regular-expressions.info/ is an awesome reference
Bonus Points: This regex does not match non-ASCII alphas. Unfortunately, the regex engine in most browsers does not support named character sets, but there are some libraries to help with that.
For languages/platforms that do support named character sets, you can use /^[\p{Letter}\d\_\-\s]+$/
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