Problem
I’m looking for a regex that only accepts alphanumeric characters. So far, everything I’ve tried works only if the string is alphanumeric, that is, it contains both a letter and a number. I just want one that allows me to choose between the two options rather than requiring me to use both.
Asked by User
Solution #1
/^[a-z0-9]+$/i
^ Start of string
[a-z0-9] a or b or c or ... z or 0 or 1 or ... 9
+ one or more times (change to * to allow empty string)
$ end of string
/i case-insensitive
new information (supporting universal characters)
You may obtain a list of Unicode characters here if you require this regexp to support universal characters.
/([a-zA-Z0-9u0600-u06FFu0660-u0669u06F0-u06F9 _.-]+)/([a-zA-Z0-9u0600-u06FFu0660-u0669u06F0-u06F9 _.-]+)/([a-zA-Z0-9u0600-u06FFu0660-u0669u06F $/
Persian will be supported by this.
Answered by Greg
Solution #2
This would work if you wanted to return a replacement result:
var a = 'Test123*** TEST';
var b = a.replace(/[^a-z0-9]/gi,'');
console.log(b);
This would return:
Test123TEST
The gi is required since it means global (not just on the first match) and case-insensitive, which is why I used a-z rather than a-zA-Z. And the “anything not in these brackets” inside the brackets means “anything not in these brackets.”
WARNING: Alphanumeric is fantastic if that’s all you need. However, if you’re utilizing this in an international market to represent something like a person’s name or a location, you’ll need to care for unicode characters, which this won’t do. For example, if your name is “lvarö,” it will be spelled “lvar.”
Answered by Volomike
Solution #3
Make use of the term “character class.” A [a-zA-Z0-9_]+$ is identical to the following:
^\w+$
Explanation:
If you don’t want to match the underscore, use /[w]| /g.
Answered by Chase Seibert
Solution #4
/^([a-zA-Z0-9 _-]+)$/
The preceding regex permits spaces within a string but excludes special characters. Only a-z, A-Z, 0-9, Space, Underscore, and dashes are permitted.
Answered by Gayan Dissanayake
Solution #5
^\s*([0-9a-zA-Z]*)\s*$
or, if you want a minimum of one character:
^\s*([0-9a-zA-Z]+)\s*$
A set of characters is indicated by square brackets. is the start of the input. $ denotes the end of the input (or newline, depending on your options). The letter s stands for whitespace.
There is no need for the whitespace before and after.
The parenthesis serve as a grouping operator, allowing you to extract the data you require.
EDIT: my incorrect use of the w character set has been removed.
Answered by cletus
Post is based on https://stackoverflow.com/questions/388996/regex-for-javascript-to-allow-only-alphanumeric