Reputation: 2553
I need to write a regex expression to use with JS .match() function. The objective is to check a string with multiple alternatives. For example, I want to return true in below code if mystr contains word1 or word2 or word3
mystr1 = "this_is_my_test string_containing_word2_where_i_will_perform_search";
mystr2 = "this_is_my_test string_where_i_will_perform_search";
myregex = xxxxxx; // I want help regarding this line so that
if(mystr1.match(myregex)) return true; //should return true
if(mystr2.match(myregex)) return true; //should NOT return true
Any help please?
Upvotes: 7
Views: 26540
Reputation: 5822
If you are not making use of your matches then I might be inclined to using the test()
method and including the i
flag as well.
if( /word1|word2|word3/i.test( mystr1 ) ) return true; //should return true
if( /word1|word2|word3/i.test( mystr2 ) ) return true; //should NOT return true
Upvotes: 0
Reputation: 16714
The regex is: /word1|word2|word3/
Be aware that, as well as your code would work, you are actually not using the method you need.
string.match(regex)
-> returns an array of matches. When evaluated as boolean, it would return false
when empty (that's why it works).regex.test(string)
-> is what you should use. It evaluates if the string matches the regex and return a true
or false
.Upvotes: 2
Reputation: 34895
So use the OR |
in your RegEx:
myregex = /word1|word2|word3/;
Upvotes: 14