问题
I want to find all the words on my webpage that match any of the words in a Javascript array, and highlight them (wrap them in special span tags). What's the easiest way to do this? I use jquery.
回答1:
Not perfect, but simple and may work:
var regex = /(Hello|Goodbye)/g;
$('*').each(function() {
var $this = $(this);
var text = $this.text();
if (regex.test(text)) {
$this.html(
$this.html().replace(regex, '<span>$1</span>')
);
}
});
http://jsfiddle.net/pdWAn/
回答2:
Try this these methods
highlightWord(["text1", "text2"]);
function highlightWord(searchArray, container)
{
var bodyText;
if(container)
bodyText = container.html();
else
bodyText = $(document.body).html();
container = container || $(document.body);
for (var i = 0; i < searchArray.length; i++) {
bodyText = doHighlight(bodyText, searchArray[i]);
}
container.html(bodyText);
return true;
}
function doHighlight(bodyText, searchTerm)
{
var highlightStartTag = "<span style='color:blue; background-color:yellow;'>";
var highlightEndTag = "</span>";
var newText = "";
var i = -1;
var lcSearchTerm = searchTerm.toLowerCase();
var lcBodyText = bodyText.toLowerCase();
while (bodyText.length > 0) {
i = lcBodyText.indexOf(lcSearchTerm, i+1);
if (i < 0) {
newText += bodyText;
bodyText = "";
} else {
if (bodyText.lastIndexOf(">", i) >= bodyText.lastIndexOf("<", i)) {
if (lcBodyText.lastIndexOf("/script>", i) >= lcBodyText.lastIndexOf("<script", i)) {
newText += bodyText.substring(0, i) + highlightStartTag + bodyText.substr(i, searchTerm.length) + highlightEndTag;
bodyText = bodyText.substr(i + searchTerm.length);
lcBodyText = bodyText.toLowerCase();
i = -1;
}
}
}
}
return newText;
}
来源:https://stackoverflow.com/questions/6987328/how-do-you-highlight-all-the-words-on-the-page-that-match-an-array-of-words