javascript - Search and highlight in html with multiple keywords as a single string -
in javascript, given html string tags like: this string has different fonts.
<b>this</b> <i>string</i> <span style="background-color: rgb(212, 239, 181);">has</span> <b>different</b> <i>fonts</i>.
when user searches search term multiple words "different fonts".
how can add highlighting make html string like:
<b>this</b> <i>string</i> <span style="background-color: rgb(212, 239, 181);">has</span> <span class="highlight"> <b>different</b> <i>fonts</i> </span>.
please note search term treated single string if words in quote, cannot search , highlight each word individually.
utilize innerhtml + str.replace in javascript
start placing div around content.
<div id='content'>
set content variable in javascript.
var xyz = document.getelementbyid("content").innerhtml;
explode users search array , use javascripts str.replace filter through content variable.
var needle = document.getelementbyid("needle").innerhtml; var splitarray = str.split(" "); (var = 0; < splitarray.length; i++) { /* code below mentioned later */ xyz = str.replace("<span class='highlight'>" + splitarray[i] + "</span>", splitarray[i]); }
set replace text to:
"<span class='highlight'>" + /* needle (see above) */ + "</span>"
to keep them consecutive, go through xyz string , replace span tags 3 character replacements:
var replaces = xyz.replace("</span>", "~/s"); var replaces = replaces.replace("<span class='bold'>", "~/b");
then loop through string using indexof. if there split array has index of previous split array.length + 7 know consecutive. 7 comes space between words + 3 character replacement made start , end spans: 7 = 3 + 1 + 3
var countr = 0; // create loop here var indxstr = replaces.indexof(splitarray[0],countr); if (replaces.indexof(splitarray[1] == (indxstr.length + 7) { // far! } else { // previous index , add 1 (so not repeat) countr = replaces.indexof(indxstr) + 1; } // end loop here
where put "create loop here" want loop can find multiple occurrences of string (indexof gets first, why used countr variable avoid previous search). "good far" comment continue on same style of loop, loop handle 2 words "different fonts" should there 3 "has different fonts" need loop counts per word ->
for (var q = 0; q < splitarray.length; q++) { if (q > 1) { if (replaces.indexof(splitarray[q] == (splitarray[q - 1].length + 7) { } } } else { // use original code above splitarray[1] , indxstr } // etc~
Comments
Post a Comment