JavaScript在字符串中查找名称

时间:2013-05-07 23:57:44

标签: javascript string algorithm search

用于搜索给定字符串以查找大量名称的优秀JavaScript库。

例如,给定1000个政治家名单的列表,查找字符串中的每个实例并将其包装在span中。

优先事项是表现越来越多的名字,以及确定例如“托尼布莱尔”,“托尼布莱尔三世”之间差异的准确性。

例如,这个:

["Tony Blair", "Margaret Thatcher", "Tony Blairite", "Tony Blair III", etc...]
"The best PM after Tony Blair was Margaret Thatcher."

变为:

"The best PM after <span class="mp">Tony Blair</span> was <span class="mp">Margaret Thatcher</span>."

1 个答案:

答案 0 :(得分:0)

var names = ['foo','bar'];
var content = "this foo is bar foobar  foo ";
for (var c=0,l=names.length;c<l;c++) {
  var r = new RegExp("\\b("+names[c]+")\\b","gi");
  content = content.replace(r,'<span class="mp">$1</span>');
}