_("test1: "+ ("slayers get more".match(RegExp("^" + "slayers get magic"), "g")));
I am expecting the result “slayers get m” but instead I get null?
Typing a regexp literal instead does work.
Another question: How do I get it to match whole words only, so that the result would be “slayers get” ?
thx
The
"g"should be the second argument toRegExp(), not the second argument to.match(). (Though with your regex starting with a^to match from the beginning of the string you don’t need"g"at all.)In addition it would be “more correct” to use
newas follows:However I believe in the case of
RegExp()it works with or withoutnew.nullis the correct result for that string and that regex, because it doesn’t match. That is, a regex is either going to match or not (in this case not), it doesn’t return the portion of the string that made a partial match.It seems like what you really want to do is return that part of the first string that matches the beginning of the second string, up to but not including the first different character. If so, try this:
Building on the same idea as my previous function, just compare one word at a time:
This splits both strings up into individual words, compares one word at a time until there is a mismatch, and returns the words that matched up until that point (or an empty string if none matched).
DEMO: http://jsfiddle.net/j8zsU/1/