RegEx for Javascript to allow only alphanumeric

RegEx for Javascript to allow only alphanumeric

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.


Solution 1:


^         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

Solution 2:

If you wanted to return a replaced result, then this would work:

var a = 'Test123*** TEST';
var b = a.replace(/[^a-z0-9]/gi,'');

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”.

Related:  What does `precision mediump float` mean?

Solution 3:

Use the word character class. The following is equivalent to a ^[a-zA-Z0-9_]+$:



  • ^ start of string
  • \w any word character (A-Z, a-z, 0-9, _).
  • $ end of string

Use /[^\w]|_/g if you don’t want to match the underscore.

Solution 4:

/^([a-zA-Z0-9 _-]+)$/

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.

Solution 5:


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.

Solution 6:

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


Related:  Getting Error Promise is undefined in IE11

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);


Refered:Regular expression for alphanumeric in Angularjs