Adding mutiple values in regex for pattern match

Advertisements

I am trying to add multiple strings in regex and then test them against certain value to see if that string exists.

 var pattern = new RegExp("^"+"ABC","i");
 var patternMatch= pattern.test(SomeArray[0]);

Now I require to add multiple string values in regex and then test if it exists in array.
Something like this :

var pattern = new RegExp("^"+"ABC" , "XYZ","i"); 
var patternMatch= pattern.exists(SomeArray[0]);

patternMatch should return true if array contains either of ABC or XYZ.
Can something like this be achieved

>Solution :

To find multiple patterns, join them with | to specify alternatives.

var pattern = new RegExp("^(" + "ABC" + "|" + "XYZ" + ")", "i");

Note that you need to put () around the alternatives. Otherwise the ^ anchor will only apply to the first alternative.

Leave a ReplyCancel reply