Regular Expression for alphanumeric and underscores - Stack …
Hello Neha,
Yes, you can use a regular expression to check if a string contains only upper and lowercase letters, numbers, and underscores. Here are three solutions:
Using a character class ([A-Za-z0-9_]) and the ^ and $ anchors to match the entire string:
const regex = /^[A-Za-z0-9_]+$/; const isValid = regex.test(“your_string_here”);
^ asserts the start of the string. [A-Za-z0-9_] matches any uppercase or lowercase letter, digit, or underscore.
- allows one or more occurrences of the character class. $ asserts the end of the string. test() is used to test if the string matches the regular expression.
Hey NehaGupta,
Using the shorthand character class \w, which matches word characters (letters, digits, and underscores):
const regex = /^[\w]+$/; const isValid = regex.test(“your_string_here”);
[\w] is equivalent to [A-Za-z0-9_]. The rest of the regex and its functionality are the same as in the first solution.
Hello Neha,
Using a negated character class ([^]) to match any character that is not an uppercase or lowercase letter, digit, or underscore, and checking if it doesn’t exist in the string:
const regex = /[^A-Za-z0-9_]/; const isValid = !regex.test(“your_string_here”);
[^A-Za-z0-9_] matches any character that is not in the specified range (uppercase and lowercase letters, digits, and underscores). !regex.test() checks if the string does not contain any characters outside the specified range.