Highlight search terms (select only leaf nodes)

前端 未结 7 903
故里飘歌
故里飘歌 2020-11-30 14:20

I would like to highlight search terms on a page, but not mess with any HTML tags. I was thinking of something like:

$(\'.searchResult *\').each(function()          


        
7条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-30 15:08

    My reputation is not high enough for a comment or adding more links, so I am sorry to write a new answer without all references.

    I was interested in the performance of the mentioned solutions above and added some code for measurement. To keep it simple I added only these lines:

    var start = new Date();
    // hightlighting code goes here ...
    var end = new Date();
    var ms = end.getTime() - start.getTime();
    jQuery("#time-ms").text(ms);
    

    I have forked the solution of Anurag with these lines and this resulted in 40-60ms in average.

    So I forked this fiddle and made some improvements to fit my needs. One thing was the RegEx-escaping (plz see the answer from CoolAJ86 in "escape-string-for-use-in-javascript-regex" in stackoverflow). Another point was the prevention of a second 'new RegExp()', as the RegExp.test-function should ignore the global flag and return on the first matching (plz see javascript reference on RegExp.test).

    On my machine (chromium, linux) I have runtimes about 30-50ms. You can test this by yourself in this jsfiddle.

    I also added my timers to the highest rated solution of galambalazs, you can find this in this jsFiddle. But this one has runtimes of 60-100ms.

    The values in milliseconds become even higher and of much more importance when running (e.g. in Firefox about a quarter of a second).

提交回复
热议问题