Posts

Showing posts from September, 2008

HTML Search Text and Highlight

Jumping straight to the solution: //modified search function 1. function searchtext(inputText, searchString) { 2. 3. 4. //building RegExp object for the search text g-global match,i-ignore case 5. var myregexp = new RegExp ( searchString , "gi"); 6. 7. //custom replace function just to highlight the match word in the html source 8. var myNewString = inputText . replace( myregexp, 9. function ( matchTxt,key,txt) { 10. return "<span style='background-color:red;>'" + matchTxt + "</span>"; 11. } ) ; 12. 13. //return the new highlighted text 14. return myNewString; 15. 16. } I think going through the code will be just self explanatory as the solution is straight-forward.But did you see some weird implementation ? Bingo! you found it :) It's the custom replace function. Let's get dirty with some syntax explanation and we will be soon back with the ex