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.
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.
Java - String matches() Methodmatches(regex) yields exactly the same result as the expression Pattern.
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.
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.
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