要突出显示字符串中搜索的确切单词,而不仅仅是字符串的开头,可以使用正则表达式来实现。以下是一种可能的方法:
highlightWord(word, text)
。/\bword\b/g
模式来匹配整个字符串中的确切单词。其中,\b
表示单词的边界,g
表示全局匹配。replace()
函数将匹配到的单词替换为带有突出显示样式的字符串。例如,可以使用HTML的<span>
标签来添加样式,如<span style="background-color: yellow;">word</span>
。以下是一个示例代码:
function highlightWord(word, text) {
var regex = new RegExp("\\b" + word + "\\b", "g");
var highlightedText = text.replace(regex, '<span style="background-color: yellow;">$&</span>');
return highlightedText;
}
var inputText = "This is a sample text. Sample is the keyword.";
var keyword = "sample";
var highlightedText = highlightWord(keyword, inputText);
console.log(highlightedText);
输出结果为:This is a <span style="background-color: yellow;">sample</span> text. <span style="background-color: yellow;">Sample</span> is the keyword.
这样,函数将会突出显示字符串中所有匹配到的确切单词。你可以根据需要自定义样式,并将该函数应用于任何字符串搜索的场景中。
领取专属 10元无门槛券
手把手带您无忧上云