我有一系列名字;
["Agent 1", "Agent 12", "Agent 2"]
我将收到一个我需要搜索的字符串(可能包含或不包含数组中的一个单词),如果找到匹配项,则返回数组值。
例如,我可能会收到字符串。
I spoke to Agent 1 the other day.
我使用以下算法搜索任何匹配项。
for (var i in agent_names) {
var name = agent_names[i];
if (msg.toLowerCase().indexOf(name.toLowerCase()) !== -1) {
return agent_names[i];
}
}
return null;
这适用于Agent 1
。但是,如果相同的消息说;
I spoke to Agent 12 the other day.
算法仍将匹配Agent 1
,因为它是字符串的一部分。
基本上,我正在寻找最合适的搜索而不是第一次适合。 indexOf
在这种情况下不起作用。
我能想到这样做的唯一方法是通过信件强制执行并存储最长的匹配。但这似乎效率低下?
答案 0 :(得分:1)
在匹配循环开始之前对单词数组进行排序:
agent_names = agent_names.sort(function(i,j){return i.length < j.length})
for (var i in agent_names) {
var name = agent_names[i];
if (msg.toLowerCase().indexOf(name.toLowerCase()) !== -1) {
return agent_names[i];
}
}
return null;
答案 1 :(得分:0)
按长度降序排列字符串列表。
答案 2 :(得分:0)
使用正则表达式。
reg = '\\b(' + name.toLowerCase() + ')\\b';
if (msg.toLowerCase().indexOf(reg) !== -1) {
return agent_names[i];
}
这将确保您在word boundaries
内查找搜索字词,以便在查找“代理1”时不会意外匹配“代理13”或“代理12”
答案 3 :(得分:0)
.match(/\d+/)
将从字符串.So商店号码数组agent_names
返回数字,并按Math.max
获取最大数字。然后您可以用replace
替换字符串。
var name_arr = [];
for (var i in agent_names) {
name_arr.push(agent_names[i].match(/\d+/));//store number array
}
replace_text = Math.max.apply(Math,name_arr);//get greatest number
msg = msg.replace("1",replace_text); //replace with greatest number
console.log(msg);