Using javascript (or Jquery) how would I compare a string of text to an array and return matching values?
For example if I have an array:
var names = ["John", "Mary", "George"];
And I have a string:
var sentence = "Did Mary go to the store today?";
I want to compare the string and the array and return the matching word, in this example "Mary".
I have searched and everything I have found seems to be comparing for a specific string. What I am looking for is matching PARTIALS.
Thanks!
To avoid Johnathon matching John, you'll want to build a regular expression:
var names = ["John", "Mary", "George"];
var regex = new RegExp("(^|[^a-zA-Z0-9])(" + names.join("|") + ")([^a-zA-Z0-9]|$)", "g");
regex.test("Did Johnathon go to the store today?"); // false
regex.test("Did John go to the store today?"); // true
You want to match the name if the name is at the beginning of the string or a non alpha numeric character precedes it (^|[^a-zA-Z0-9])
, AND if the name is at the end of the string or a non alpha numeric character succeeds it ([^a-zA-Z0-9]|$)
. Hence the two captures before and after the list of names.
To collect the names:
var matches = [];
var sentence = "Did John or Mary go to the store today?";
sentence.replace(regex, function(match, $1, $2, $3) {
matches.push($2);
});
console.log(matches);
And a quick reusable function:
function getMatchingWords(words, s) {
var matches = [],
regex = new RegExp("(^|[^a-zA-Z0-9])(" + words.join("|") + ")([^a-zA-Z0-9]|$)", "g");
s.replace(regex, function(match, $1, $2, $3) {
matches.push($2);
});
return matches;
}
var matches = getMatchingWords(["John", "Mary", "Billy"], "Did John or Mary go to the store today?");