Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match a string against an array of pattern in Javascript?

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?

like image 416
fatCop Avatar asked Apr 06 '15 07:04

fatCop


People also ask

How do you search a string for a 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.


2 Answers

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
like image 197
Amadan Avatar answered Sep 20 '22 05:09

Amadan


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$"];
like image 22
Avinash Raj Avatar answered Sep 21 '22 05:09

Avinash Raj