I'm trying to search for strings in an html page, I have an object with 1000 names in it and I need to find if those names exist in the html document. If they do exist i then need to wrap them in a span or something and apply a class.
I've been using this jQuery Highlight Plugin but it takes about 17 seconds to scan and highlight the whole page, this obviously varies depending on how many different names there are on the page.
I've tried a few different plugins but haven't found anything faster, is there a way to do this in vanilla JS that is faster? It only needs to work in Chrome.
Any help would be really appreciated.
Thanks
Edit: Structure of the object which holds names:
var PEOPLE = { "fred" : { loaded : false, elements : [] }, "dave" : { loaded : false, elements : [] }, "bob" : { loaded : false, elements : [] } }
Plain javascript.
Basically I iterate through your object and extract all the relevant names. Once I have this, I pass the array to the highlightString function where I join all the strings you want to match with the pipe character and create a regular expression that runs globally and ignores case. This results in the div being searched only being searched once. This should result in a considerable speedup.
var PEOPLE = {
"fred" : {
loaded : false,
elements : []
},
"dave" : {
loaded : false,
elements : []
},
"bob" : {
loaded : false,
elements : []
}
},
name,
search = [];
for (name in PEOPLE) {
search.push(name);
}
function highlightStrings(input, toMatch) {
var reg = new RegExp('(' + toMatch.join('|') + ')', "gi");
input.innerHTML = input.innerHTML.replace(reg, '<span class="myHighLight">$1</span>');
}
highlightStrings(document.getElementById("test"), search);
.myHighLight {background-color:yellow;}
<div id="test">
test1 test2 fred test4 test5 test6 test7 test8 dave test10 test11 test12 bob test14 test15
</div>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments