7

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?

2
  • The regex would check if the str contains any of the options: word1, word2 or word3? Commented Jan 11, 2013 at 15:52
  • yes, that is my intention ... but all words will be in a string in comma separated format. Commented Jan 11, 2013 at 16:08

3 Answers 3

14

So use the OR | in your RegEx:

myregex = /word1|word2|word3/;
Sign up to request clarification or add additional context in comments.

1 Comment

So, if my words are in a variable (comma separated), should this work? s = $var.replace(",","|"); myregex = new RegExp(s,"i");
2

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.