В общем случае вам потребуется проанализировать HTML-код, чтобы убедиться, что вы выделяете только ключевые слова, а не невидимый текст или код (например, атрибуты alt text для изображений или фактическую разметку). Если вы делаете так, как предложил Джесси Халлетт :
$('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-документов (т.е. без открытых угловых скобок без закрывающих угловых скобок и т. Д.), То вы сможете сканировать текст в поисках данных без тегов, без атрибутов, которые можно дальше-размеченный.
Вот некоторый Javascript, который может это сделать:
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;
}