highlightWords

Highlight Words

이 스크립트는 직접 설치하는 용도가 아닙니다. 다른 스크립트에서 메타 지시문 // @require https://update.greasyfork.org/scripts/535935/1588732/highlightWords.js을(를) 사용하여 포함하는 라이브러리입니다.

이 스크립트를 설치하려면 Tampermonkey, Greasemonkey 또는 Violentmonkey와 같은 확장 프로그램이 필요합니다.

You will need to install an extension such as Tampermonkey to install this script.

이 스크립트를 설치하려면 Tampermonkey 또는 Violentmonkey와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 Tampermonkey 또는 Userscripts와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 Tampermonkey와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 유저 스크립트 관리자 확장 프로그램이 필요합니다.

(이미 유저 스크립트 관리자가 설치되어 있습니다. 설치를 진행합니다!)

이 스타일을 설치하려면 Stylus와 같은 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 Stylus와 같은 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 Stylus와 같은 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 유저 스타일 관리자 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 유저 스타일 관리자 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 유저 스타일 관리자 확장 프로그램이 필요합니다.

(이미 유저 스타일 관리자가 설치되어 있습니다. 설치를 진행합니다!)

function escapeRegex(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

function highlightWords(words, highlightClass = 'highlight') {
  if (!words || words.length === 0) return;

  // Create patterns for words and phrases
  const patterns = words.map(word => {
    const trimmed = word.trim();
    if (trimmed.includes(' ')) {
      // Handle phrases
      const parts = trimmed.split(/\s+/);
      const escapedParts = parts.map(escapeRegex);
      const pattern = escapedParts.map(part => `\\b${part}\\b`).join('\\s+');
      return { pattern, numWords: parts.length };
    } else {
      // Handle single words
      const escaped = escapeRegex(trimmed);
      const pattern = `\\b${escaped}\\b`;
      return { pattern, numWords: 1 };
    }
  });

  // Sort patterns by number of words descending to match longer phrases first
  patterns.sort((a, b) => b.numWords - a.numWords);

  // Create the regex pattern by joining all patterns with '|'
  const regexPattern = patterns.map(p => p.pattern).join('|');
  const regex = new RegExp(regexPattern, 'gi');

  // Select text nodes excluding script, style, and already highlighted elements
  const xpath = `//text()[not(ancestor::script) and not(ancestor::style) and not(ancestor::*[contains(concat(" ", normalize-space(@class), " "), " ${highlightClass} ")])]`;
  const textNodes = document.evaluate(xpath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

  for (let i = 0; i < textNodes.snapshotLength; i++) {
    const textNode = textNodes.snapshotItem(i);
    const text = textNode.nodeValue;
    const matches = [...text.matchAll(regex)];

    if (matches.length > 0) {
      const fragment = document.createDocumentFragment();
      let lastIndex = 0;

      for (const match of matches) {
        const offset = match.index;
        if (offset > lastIndex) {
          fragment.appendChild(document.createTextNode(text.slice(lastIndex, offset)));
        }
        const span = document.createElement('span');
        span.className = highlightClass;
        span.textContent = match[0];
        fragment.appendChild(span);
        lastIndex = offset + match[0].length;
      }

      if (lastIndex < text.length) {
        fragment.appendChild(document.createTextNode(text.slice(lastIndex)));
      }

      textNode.parentNode.replaceChild(fragment, textNode);
    }
  }
}