I need to find a reg ex that only allows alphanumeric. So far, everyone I try only works if the string is alphanumeric, meaning contains both a letter and a number. I just want one what would allow either and not require both.
/^[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
If you wanted to return a replaced result, then this would work:
var a = 'Test123*** TEST'; var b = a.replace(/[^a-z0-9]/gi,''); console.log(b);
This would return:
Note that the gi is necessary because it means global (not just on the first match), and case-insensitive, which is why I have a-z instead of a-zA-Z. And the ^ inside the brackets means “anything not in these brackets”.
WARNING: Alphanumeric is great if that’s exactly what you want. But if you’re using this in an international market on like a person’s name or geographical area, then you need to account for unicode characters, which this won’t do. For instance, if you have a name like “Âlvarö”, it would make it “lvar”.
Use the word character class. The following is equivalent to a
- ^ start of string
- \w any word character (A-Z, a-z, 0-9, _).
- $ end of string
/[^\w]|_/g if you don’t want to match the underscore.
the above regex allows spaces in side a string and restrict special characters.It Only allows
a-z, A-Z, 0-9, Space, Underscore and dash.
or, if you want a minimum of one character:
Square brackets indicate a set of characters. ^ is start of input. $ is end of input (or newline, depending on your options). \s is whitespace.
The whitespace before and after is optional.
The parentheses are the grouping operator to allow you to extract the information you want.
EDIT: removed my erroneous use of the \w character set.
This will work
It accept only alphanumeriuc characters alone:
test cases pased :
dGgs1s23 - valid 12fUgdf - valid, 121232 - invalid, abchfe - invalid, abd()* - invalid, 42232^5$ - invalid
You can also try this one. this expression satisfied at least one number and one character and no other special characters
in angular can test like:
$scope.str = '12fUgdf'; var pattern = new RegExp('^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$'); $scope.testResult = pattern.test($scope.str);