Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 212
Richard Avatar asked Jul 06 '11 21:07

Richard


People also ask

How do you know if a string matches a pattern?

To check if a String matches a Pattern one should perform the following steps: Compile a String regular expression to a Pattern, using compile(String regex) API method of Pattern. Use matcher(CharSequence input) API method of Pattern to create a Matcher that will match the given String input against this pattern.

Does string match regex?

Java - String matches() Methodmatches(regex) yields exactly the same result as the expression Pattern.

What property can we use to check if a string matches a regular expression?

You can determine whether the regular expression pattern has been found in the input string by checking the value of the returned Match object's Success property. If a match is found, the returned Match object's Value property contains the substring from input that matches the regular expression pattern.


1 Answers

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.

like image 167
user113716 Avatar answered Oct 07 '22 16:10

user113716