HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptCritical

Check whether a string matches a regex in JS

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
checkwhethermatchesregexstring

Problem

I want to use JavaScript (I can also use jQuery) to do check whether a string matches the regex ^([a-z0-9]{5,})$, and get a true or false result.

match() seems to check whether part of a string matches a regex, not the whole thing. Does it solve the problem? Can I adapt it to solve the problem? How?

Solution

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.

Context

Stack Overflow Q#6603015, score: 1847

Revisions (0)

No revisions yet.