I need a regular expression to test a string. The string can only contain English letters, number, hyphen and underscore.
previously I have one to test a string whether it only contains positive numbers(zero included); I used:
if(!/^\d+$/.test(number)) {
alert('..bla');
} else {
return true;
};
So I want a similar one. I have read:
Regular expressions and Chinese;
and Regex Letters, Numbers, Dashes, and Underscores;
But these two does not seem to fix my problem.
!/[a-zA-Z0-9\-\_]+$/.test('_-bla') // return false
!/[a-zA-Z0-9\-\_]+$/.test('_-bl我a') // return false
!/[a-zA-Z0-9\-\_]+$/.test('_-bl我') // return true
!/[a-zA-Z0-9\-\_]+/.test('_-bl我') // return false
!/[a-zA-Z0-9\-\_]+/.test('_-bl我a') // return false
Thanks in advance. :)
Use ^[-\w]+$. \w matches digits, alphabets, _.
/^[-\w]+$/.test('_-bla') // true
/^[-\w]+$/.test('_-bl我a') // false
/^[-\w]+$/.test('_-bl我') // false
/^[-\w]+$/.test('_-bl我') // false
/^[-\w]+$/.test('_-bl我a') // false
I assume you're looking for this output. Add the caret (^) which means start of string and ($) meaning end of string to your regular expressions.
/^[a-zA-Z0-9_-]+$/.test('_-bla'); // True
/^[a-zA-Z0-9_-]+$/.test('_-bl我a'); // False
/^[a-zA-Z0-9_-]+$/.test('_-bl我'); // False
/^[a-zA-Z0-9_-]+$/.test('_-bl我'); // False
/^[a-zA-Z0-9_-]+$/.test('_-bl我a'); // False
You can just use \w instead which matches word characters (a-z, A-Z, 0-9, _)
/^[\w-]+$/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With