TP:以下两种方法多次匹配也不会造成匹配结果混乱的问题
- 第一种方法
let keyword = ["red", "color", ">"];
let tableData = {
MatchCompanyName: "color fjkfffs red >",
};
function highlightKeywords(data, keywords) {
let matchCompanyName = data.MatchCompanyName;
let result = '';
let lastIndex = 0;
const regex = new RegExp(keywords.join('|'), 'gi');
matchCompanyName.replace(regex, (match, index) => {
result += matchCompanyName.slice(lastIndex, index);
result += `<span class="highlighted">${match}</span>`;
lastIndex = index + match.length;
});
result += matchCompanyName.slice(lastIndex);
return result;
}
let highlightedText = highlightKeywords(tableData, keyword);
console.log(highlightedText);
- 第二种
let keyword = ["red", "color", ">"];
let tableData = {
MatchCompanyName: "color fjkfffs red >",
};
function highlightKeywords(data, keywords) {
let matchCompanyName = data.MatchCompanyName;
let highlights = [];
keywords.forEach((word) => {
const regex = new RegExp(word, 'gi');
let match;
while ((match = regex.exec(matchCompanyName)) !== null) {
highlights.push({ start: match.index, end: regex.lastIndex });
}
});
highlights.sort((a, b) => b.start - a.start);
highlights.forEach((highlight) => {
matchCompanyName =
matchCompanyName.slice(0, highlight.start) +
'<span class="highlighted">' +
matchCompanyName.slice(highlight.start, highlight.end) +
'</span>' +
matchCompanyName.slice(highlight.end);
});
return matchCompanyName;
}
let highlightedText = highlightKeywords(tableData, keyword);
console.log(highlightedText);
总结:第一种方法通过一次遍历来找到所有的匹配项并构建新的字符串,避免在替换时频繁地操作字符串。这种方式减少了字符串的拼接操作,提高了性能。