word2 (when it exists):
This is a test. Here is word1 and here is word2, which may or may not exist.
I tried these:
This will match only
word1 regardless if
word2 exists or not.
This will match both but only if both exists.
I need a regex to match word1 and word2 - which may or may not exist.
Best How To :
var str = "This is a test. Here is word1 and here is word2, which may or may not exist.";
var matches = str.match( /word1|word2/g );
//-> ["word1", "word2"]
String.prototype.match will run a regex against the string and find all matching hits. In this case we use alternation to allow the regex to match either
You need to apply the global flag to the regex so that
match() will find all results.
If you care about matching only on word boundaries, use