我正在尝试突出显示与我的搜索文字的任何字词匹配的所有文字。
假设搜索文字所有文字
我的查询返回所有记录,其中的文本包含上述任何文字(与MSSQL中的文本搜索相同)
现在我需要用搜索中的任何单词突出显示所有匹配项。我目前的代码只能突出显示全文。
我当前的代码:
getHighlightedText(text, higlight) {
let parts = text.split(new RegExp(`(${higlight})`, 'gi'));
return <span> { parts.map((part, i) =>
<span key={i} style={part.toLowerCase() === higlight.toLowerCase() ? { color: '#93C74B' } : {} }>{part}</span>)
} </span>;
}
提前致谢。
答案 0 :(得分:1)
您可以使用replace
执行此操作,以下是一个示例:
const getHighlightedText = (text, higlight) => {
let groups = higlight.split(" ").map(v => `(${v})`).join("|");
return "<span>" + text.replace(new RegExp(groups, "gi"), g => `<span style="color:#93C74B">${g}</span>`) + "<span>";
}
let text = "Some text for testing";
let higlight = "TEXT testing";
document.write(getHighlightedText(text, higlight));
这样做首先从搜索到的字符串生成正则表达式,具有此结构的正则表达式(word1)|(word2)....
,然后使用replace
将所有这些单词替换为<span>
元素不同的文字颜色。如果您想了解有关使用replace
功能的更多信息,可以执行HERE
答案 1 :(得分:0)
可以通过方法replace
完成:
getHighlightedText(text, higlight) {
let kws = higlight.replace(/ /g, "|");
return text.replace(new RegExp(`(${kws})`, "gi"),
'<span key="$1" style="color: #93C74B;">$1</span>');
}
答案 2 :(得分:0)
在这个Demo中,我编写了一个使用动态RegExp对象的自定义函数,因此可以重用它。它使用replace()
并执行以下操作:
采取2个参数:
1. a String that needs to be searched
2. a variable String that will be interpolated inside of a RegExp Object.
3. Every match will be wrapped in a `<mark>` tag.
RegExp的语法与正则表达式文字不同, one important difference is escaping by \
is needed even for meta flags 就像\w
一样需要进行转义:\\w
。
var str = document.querySelector('main').innerHTML;
function markText(str, qry) {
var rgx = new RegExp('\\b' + qry + '\\b', 'gi');
var res = str.replace(rgx, `<mark>${qry}</mark>`);
return res;
}
document.querySelector('main').innerHTML = markText(str, "Chuck Norris");
<main>
<p>Scientists believe the world began with the "Big Bang". Chuck Norris shrugs it off as a "bad case of gas". Chuck Norris actually can get blood from a turnip...and from whatever the hell else he wants. There is no chin behind Chuck Norris' beard. There is only another fist. Someone once videotaped Chuck Norris getting pissed off. It was called Walker: Texas Chain Saw Massacre Chuck Norris doesn't wash his clothes, he disembowels them. Chuck Norris' first job was as a paperboy. There were no survivors Chuck Norris will attain statehood in 2009. His state flower will be the Magnolia. Chuck Norris can slam a revolving door If Chuck Norris kicks a tree in a forest and no one was around, he chooses who he wants to hear it.</p>
<p>If you ask Chuck Norris what time it is, he always says, "Two seconds 'til." After you ask, "Two seconds 'til what?" he roundhouse kicks you in the face. Chuck Norris is the reason why Waldo is hiding.</p>
</main>