如何在contenteditable div中高亮含多关键词的文本?
解决contenteditable div中多词组合的高亮问题
你的代码当前的核心问题是按空格分割文本,导致[certain words]这类包含空格的匹配项被拆成"[certain"和"words]"两个独立片段,根本找不到完整的匹配项,自然无法实现高亮。
换一种更直接的思路:不需要拆分文本,直接在原始字符串上利用正则匹配结果做整体替换,不管匹配项里有没有空格都能正确处理。
方案1:保留括号的高亮
直接将整个括号匹配项包裹进高亮span:
var text = `Here is [the] sample [text] that matches the [certain words] in the given [text] and {highlight} the {words in the text}.` // 匹配所有方括号包裹的内容 const regexSquare = /\[[^\]]*\]/gm; // 匹配所有大括号包裹的内容 const regexCurly = /\{[^\}]*\}/gm; // 处理方括号内容的高亮 let highlightedText = text.replace(regexSquare, match => { return `<span class="highlight-bracket">${match}</span>`; }); // 处理大括号内容的高亮 highlightedText = highlightedText.replace(regexCurly, match => { return `<span class="highlight-curly">${match}</span>`; }); console.log(highlightedText);
方案2:仅高亮括号内的文字(去掉括号)
如果不需要保留括号,只高亮里面的内容,可以提取括号内的文本再包裹:
var text = `Here is [the] sample [text] that matches the [certain words] in the given [text] and {highlight} the {words in the text}.` const regexSquare = /\[[^\]]*\]/gm; const regexCurly = /\{[^\}]*\}/gm; // 提取方括号内的内容并高亮 let highlightedText = text.replace(regexSquare, match => { // 截取括号内的文本(去掉首尾的[和]) const content = match.slice(1, -1); return `<span class="highlight-bracket">${content}</span>`; }); // 提取大括号内的内容并高亮 highlightedText = highlightedText.replace(regexCurly, match => { // 截取括号内的文本(去掉首尾的{和}) const content = match.slice(1, -1); return `<span class="highlight-curly">${content}</span>`; }); console.log(highlightedText);
方案优势
- 直接对原始字符串做正则替换,避免了空格拆分导致的匹配断裂问题;
- 正则
/\[[^\]]*\]/gm会完整匹配从[到]的所有内容,不管中间有多少空格或字符; - 两种方案可根据需求灵活选择,适配不同的高亮场景。
内容的提问来源于stack exchange,提问作者Raja Simon
相关产品推荐
相关产品推荐

