I've two variables:
var input = "[email protected]";
var preferredPatterns = ["*@gmail.com", "*@yahoo.com", "*@live.com"];
Want to match the input with preferred pattern array. If any of the patterns matches I've to do certain task (in this example, input is a definite match). How can I match against an array of pattern in javascript?
Using exec() The exec() method is a RegExp expression method. It searches a string for a specified pattern, and returns the found text as an object. If no match is found, it returns an empty (null) object.
You can compile your patterns (if they are valid regular expressions) into one for performance:
var masterPattern = new RegExp(patterns.join('|'));
Putting it all together:
var input = '[email protected]';
var preferredPatterns = [
".*@gmail.com$",
".*@yahoo.com$",
".*@live.com$"
];
var masterPattern = new RegExp(preferredPatterns.join('|'));
console.log(masterPattern.test(input));
// true
You need to use RegExp
constructor while passing a variable as regex.
var input = '[email protected]';
var preferredPatterns = [".*@gmail\\.com$", ".*@yahoo\\.com$", ".*@live\\.com$"];
for (i=0; i < preferredPatterns.length;i++) {
if(input.match(RegExp(preferredPatterns[i]))) {
console.log(preferredPatterns[i])
}
}
Dot is a special meta-character in regex which matches any character. You need to escape the dot in the regex to match a literal dot.
As @zerkms said, you could use the below list of patterns also.
var preferredPatterns = ["@gmail\\.com$", "@yahoo\\.com$", "@live\\.com$"];
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