Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - match string against the array of regular expressions

Is there a way in JavaScript to get Boolean value for a match of the string against the array of regular expressions?

The example would be (where the 'if' statement is representing what I'm trying to achieve):

var thisExpressions = [ '/something/', '/something_else/', '/and_something_else/']; var thisString = 'else';  if (matchInArray(thisString, thisExpressions)) {  }  
like image 398
user398341 Avatar asked Apr 14 '12 09:04

user398341


People also ask

How do you match for a string in JavaScript?

match() is an inbuilt function in JavaScript used to search a string for a match against any regular expression. If the match is found, then this will return the match as an array. Parameters: Here the parameter is “regExp” (i.e. regular expression) which will compare with the given string.

Can I use regex in array?

This is possible when regex applied on this string array. But Build Regular Expression Action only can take String as a Input not a Array of Strings.

What property can we use to check if a string matches a regular expression?

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.


1 Answers

Using a more functional approach, you can implement the match with a one-liner using an array function:

ECMAScript 6:

const regexList = [/apple/, /pear/]; const text = "banana pear"; const isMatch = regexList.some(rx => rx.test(text)); 

ECMAScript 5:

var regexList = [/apple/, /pear/]; var text = "banana pear"; var isMatch = regexList.some(function(rx) { return rx.test(text); }); 
like image 172
andersh Avatar answered Sep 28 '22 02:09

andersh