일반적으로 키워드 만 강조 표시하고 보이지 않는 텍스트 나 코드 (예 : 이미지 또는 실제 마크 업을위한 대체 텍스트 속성)가 아닌지 확인하려면 HTML 코드를 구문 분석해야합니다. If you do as Jesse Hallett suggested :
$('body').html($('body').html().replace(/(pretzel)/gi, '<b>$1</b>'));
특정 키워드 및 문서와 관련된 문제가 발생합니다.예를 들어 :
<html>
<head><title>A history of tables and tableware</title></head>
<body>
<p>The table has a fantastic history. Consider the following:</p>
<table><tr><td>Year</td><td>Number of tables made</td></tr>
<tr><td>1999</td><td>12</td></tr>
<tr><td>2009</td><td>14</td></tr>
</table>
<img src="/images/a_grand_table.jpg" alt="A grand table from designer John Tableius">
</body>
</html>
이 상대적으로 간단한 문서는 단어 "테이블"에 대한 검색하여 찾을 수 있습니다,하지만 당신은 단지 포장 텍스트와 텍스트를 대체 할 경우이 끝낼 수 :
<<span class="highlight">table</span>><tr><td>Year</td><td>Number of <span class="highlight">table</span>s made</td></tr>
및 이 :
<img src="/images/a_grand_<span class="highlight">table</span>.jpg" alt="A grand <span class="highlight">table</span> from designer John <span class="highlight">Table</span>ius">
즉, 구문 분석 된 HTML이 필요합니다. HTML 구문 분석은 까다 롭습니다. 그러나 HTML 문서 (예 : 꺽쇠 괄호가없는 열린 꺽쇠 괄호 없음)에 대한 특정 품질 제어를 가정 할 수 있다면 비 태그, 비 속성 데이터를 찾을 수있는 텍스트를 스캔 할 수 있어야합니다. 추가 마크 업.
다음은 그렇게 할 수있는 몇 가지 자바 스크립트입니다 :
function highlight(word, text) {
var result = '';
//char currentChar;
var csc; // current search char
var wordPos = 0;
var textPos = 0;
var partialMatch = ''; // container for partial match
var inTag = false;
// iterate over the characters in the array
// if we find an HTML element, ignore the element and its attributes.
// otherwise try to match the characters to the characters in the word
// if we find a match append the highlight text, then the word, then the close-highlight
// otherwise, just append whatever we find.
for (textPos = 0; textPos < text.length; textPos++) {
csc = text.charAt(textPos);
if (csc == '<') {
inTag = true;
result += partialMatch;
partialMatch = '';
wordPos = 0;
}
if (inTag) {
result += csc ;
} else {
var currentChar = word.charAt(wordPos);
if (csc == currentChar && textPos + (word.length - wordPos) <= text.length) {
// we are matching the current word
partialMatch += csc;
wordPos++;
if (wordPos == word.length) {
// we've matched the whole word
result += '<span class="highlight">';
result += partialMatch;
result += '</span>';
wordPos = 0;
partialMatch = '';
}
} else if (wordPos > 0) {
// we thought we had a match, but we don't, so append the partial match and move on
result += partialMatch;
result += csc;
partialMatch = '';
wordPos = 0;
} else {
result += csc;
}
}
if (inTag && csc == '>') {
inTag = false;
}
}
return result;
}
여기서 문제는 당신이 그렇게이 그렇게 쉽지 않을 수 있습니다 강조해야 할 키워드를 제공하는 선택을하지 않아도됩니다. 단락의 중간에있는 단어 하나를 선택하고 태그로 둘러 쌀 필요가 있습니다. –