I have an array of names;
["Agent 1", "Agent 12", "Agent 2"]
I will receive a string (that may or may not contain one of the words in the array) that I need to search through and, if a match is found, return the array value.
For example, I may receive the string.
I spoke to Agent 1 the other day.
I use the following algorithm to search for any matches.
for (var i in agent_names) {
var name = agent_names[i];
if (msg.toLowerCase().indexOf(name.toLowerCase()) !== -1) {
return agent_names[i];
}
}
return null;
This works fine for Agent 1
. However if the same message said;
I spoke to Agent 12 the other day.
The algorithm will still match Agent 1
as it is part of the string.
Essentially, I am looking for a best fit search rather than first fit. indexOf
does not work in this instance.
The only way I can think of doing this is brute forcing it by letter and storing the longest match. But this seems inefficient?