JavaScript Code


How to check if string matches given regular expression in JavaScript?


If string matches given Regex

Given a string and regular expression (regex), check if the string matches the given regular expression, using JavaScript.

Solution

To check if the string str matches the regular expression regex using JavaScript, call test() method on the regex and pass str as argument to the method.

regex.test(str)

test() method returns true if the given string matches the regular expression, or false otherwise.

Programs

1. Given a string str and regular expression regex. The regular expression matches one or more characters from lowercase alphabets and numbers.

var str = 'abcd12345xyz';
var regex = /^[a-z0-9]+$/;
if ( regex.test(str) ) {
    console.log('string matches given regex');
} else {
    console.log('string does not match given regex');
}