I will be using coffeescript/javascript/jquery and I need to return true if a string contains all of my substrings.
So, lets say that I have an array of substrings 'my', 'dog', 'spot'. I need to return a true if my string is 'growing up my pet dog was named spot'. But I would need to return false if the string was 'I had a dog named spot'.
I am thinking there is a way to do this with a regular expression, but can't seem to figure it out?
An alternate method for the books:
Using the
.every
method with regex to assert word boundaries:http://jsfiddle.net/cgYTZ/
If you want to reuse the function in various parts of your application, give it a name, and provide the string to be searched as the second argument, which makes it the
this
value.The other nice thing about
.every()
is that it short-circuits iffalse
is returned, so the search stops once a non-matching word is found, making it a little more efficient.Force whole word matching
If you want to ensure that the matched string is a whole word to avoid "dog" matching "dogma" for example, you will need to make use of RegExp word boundaries:
You don't need regular expression for this - just use indexOf, check for each words, and return if any of the words was not found
Right, if the array of substrings isn't a given:
Then, to match any substring:
I got the char escaping regex I'm using to escape strings I'm passing to the
RegExp
constructor from here.