Tuesday, 30 January 2018

javascript - Check whether a string matches a regex in JS



I want to use JavaScript (can be with jQuery) to do some client-side validation to check whether a string matches the regex:



^([a-z0-9]{5,})$


Ideally it would be an expression that returned true or false.



I'm a JavaScript newbie, does match() do what I need? It seems to check whether part of a string matches a regex, not the whole thing.



Answer



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.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...