You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用正则表达式(Regex)在JavaScript中高亮字符串中的多个关键词?

Highlighting Keywords Even When Split By HTML Tags in JavaScript

Got it, let's tackle this problem step by step. You need to highlight the keywords temperature high even when part of a keyword is already wrapped in a partial highlight tag (like the hig in your example). Here's a robust solution:

The Approach

The core challenge is matching keywords that might be split up by arbitrary HTML tags. We'll:

  • Break down the keyword phrase into individual words.
  • Build a regex pattern for each word that allows any HTML tags between its characters.
  • Replace matched segments (even those with existing partial highlights) with a clean, full highlight wrapper.

The Code

function highlightKeywords(text, keywords) {
  // Split keyword phrase into individual words
  const keywordWords = keywords.split(/\s+/);
  
  // Helper function to escape regex special characters in keywords
  function escapeRegExp(str) {
    return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  }
  
  keywordWords.forEach(word => {
    // Build regex pattern: matches the word with ANY number of HTML tags between characters
    const regexSegments = word.split('').map(char => 
      `${escapeRegExp(char)}(?:<[^>]+>)*`
    );
    const regex = new RegExp(regexSegments.join(''), 'gi');
    
    // Replace matches: strip existing tags first, then apply proper highlight
    text = text.replace(regex, match => {
      const cleanWord = match.replace(/<[^>]+>/g, '');
      return `<span class="highlight">${cleanWord}</span>`;
    });
  });
  
  return text;
}

// Test it with your example
const originalText = 'The temperature is <span class="highlight">hig</span>h';
const highlightedText = highlightKeywords(originalText, 'temperature high');
console.log(highlightedText);
// Output: The <span class="highlight">temperature</span> is <span class="highlight">high</span>

How It Works

  • Regex Pattern Breakdown: For a word like high, the regex becomes h(?:<[^>]+>)*i(?:<[^>]+>)*g(?:<[^>]+>)*h. The (?:<[^>]+>)* part matches 0 or more arbitrary HTML tags between each character, so it catches split-up versions like <span class="highlight">hig</span>h.
  • Clean Replacement: When we find a match, we first strip all HTML tags from it to get the pure keyword, then wrap it in a fresh <span class="highlight"> tag. This fixes partial highlights and ensures consistent styling.
  • Case Insensitivity: The gi flags make the regex match case-insensitively and globally, so it catches all instances of the keywords regardless of capitalization.

内容的提问来源于stack exchange,提问作者ccostel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:49:05