Regex for JavaScript to allow only alphanumeric
Use /^\w+$/
to match alphanumeric characters (letters, numbers, and underscores) in JavaScript.
Example:
Unwrapping the regex syntax
Decoding the regular expression syntax can feel as cryptic as hieroglyphics without the Rosetta stone. Let's decipher it bit-by-bit:
^
: This character pins the pattern at the start of a line.[a-z0-9]
: This set looks for alphanumeric characters - a to z, 0 to 9.+
: This qualifier seeks one or more of the preceding element.$
: This symbol stakes the pattern to the end of a line./i
: This/i
flag waves for a case-insensitive search (Spare the uppercase letters! They’re innocent!). For case-sensitive matching, you can take the flag down.
Customization tips
Ever feel that the \w
shorthand is a little too generous by including underscores ('_')? You can customize the regex rules to pick and choose the characters, like excluding the underscore:
Non-Latin alphabets have long been the neglected step-children of the regex world. Not anymore. Let's include our Persian friends with some unicode magic:
Here, \p{L}
is a unicode call for any letter, while \p{N}
is a shout-out to any number. The u
flag gears the regex for Unicode.
Tricky spots and how to tackle them
Regex is like a Rubik's cube of text. Here are a few tricks to watch out for:
- Empty strings: Replace
+
with*
and you just allowed an empty string through the gate. Make sure this change aligns with your application's rules. - Special characters: To allow spaces, underscores, or dashes in your line, you need to give them special permission by expanding your regex pattern like so:
Covering all bases
In the global village of today's application design, broad alphanumeric character support across languages is vital. For wider, Unicode-based support, use the /\p{Alphabetic}\p{Number}/
property classes with the u
flag for unicode characters.
Make sure to have a DATE with a Unicode character table for more exciting character classes to invite.
Digging deeper into character sets
With regex, specificity is key. If you want to flip the tables and allow anything but alphanumeric, use the [^a-z0-9]
:
To have an alphanumeric mix with spaces, excluding punctuation and special characters, opt for:
Be careful not to trip over case sensitivity – it could lead to code bugs. Check your /i
flag settings align with your expectations.
Was this article helpful?