我在 Javascript 中有以下字符串:
Smith, Dan
我有一些 Javascript 来突出显示该字符串中与单词数组匹配的部分(基于用户的搜索输入)。因此,如果用户输入“smith d”,那么我的数组和预期输出将包含:
string = "Smith, Dan"
word[0] = "smith"
word[1] = "d"
output: <em>Smith</em>, <em>D</em>an
但是,当第二个单词包含在第一个单词中时,这种情况就会失败。例如,如果字符串是“Smith, Helen”,则会发生以下情况:
string = "Smith, Helen"
word[0] = "smith"
word[1] = "h"
output: <em>Smit<em>h</em></em>, <em>H</em>elen
我使用正则表达式进行替换,因为需要保持源文本大小写相同(因此,如果用户输入“smith”,我仍然会返回“Smith”)。
这是我的代码:
var output = "Smith, Helen";
var arText = new Array();
arText[0] = "smith";
arText[1] = "h";
for (var iw = 0; iw < arText.length; iw++) {
var term = arText[iw];
var re = new RegExp('(' + term + ')', 'gi');
output = output.replace(re, '<em>$1</em>');
}
任何人都可以建议我如何修改它,以便它忽略 em 标签中已经存在的单词吗?我想要的上述代码的输出是:
<em>Smith</em>, <em>H</em>elen
最佳答案
您的搜索似乎与单词边界有关。我不知道您所有的边缘情况,但对现有代码的添加确实会返回您寻求的输出。只要搜索涉及换行符,它也应该适用。
var output = "Smith, Helen";
var arText = new Array();
arText[0] = "smith";
arText[1] = "h";
for (var iw = 0; iw < arText.length; iw++) {
var term = arText[iw];
var re = new RegExp('(\\b' + term + ')', 'gi');
output = output.replace(re, '<em>$1</em>');
}// notice the \\b which means look for term by line break. double escape for string.
输出
"<em>Smith</em>, <em>H</em>elen"
另一个更复杂的例子
var output = "Smith, Helen butter";
var arText = new Array();
arText[0] = "smith";
arText[1] = "h";
arText[2] = "bu";
for (var iw = 0; iw < arText.length; iw++) {
var term = arText[iw];
var re = new RegExp('(\\b' + term + ')', 'gi');
output = output.replace(re, '<em>$1</em>');
}
输出
"<em>Smith</em>, <em>H</em>elen <em>bu</em>tter"
关于javascript - 突出显示字符串中匹配的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22786995/