Check whether a string matches a regex in JS
Use regex.test()
if all you want is a boolean result:
console.log(/^([a-z0-9]{5,})$/.test('abc1')); // false
console.log(/^([a-z0-9]{5,})$/.test('abc12')); // true
console.log(/^([a-z0-9]{5,})$/.test('abc123')); // true
...and you could remove the ()
from your regexp since you've no need for a capture.
Use test()
method :
var term = "sample1";
var re = new RegExp("^([a-z0-9]{5,})$");
if (re.test(term)) {
console.log("Valid");
} else {
console.log("Invalid");
}
You can use match()
as well:
if (str.match(/^([a-z0-9]{5,})$/)) {
alert("match!");
}
But test()
seems to be faster as you can read here.
Important difference between match()
and test()
:
match()
works only with strings, but test()
works also with integers.
12345.match(/^([a-z0-9]{5,})$/); // ERROR
/^([a-z0-9]{5,})$/.test(12345); // true
/^([a-z0-9]{5,})$/.test(null); // false
// Better watch out for undefined values
/^([a-z0-9]{5,})$/.test(undefined); // true