Slow highlighting in Firefox

后端 未结 2 445
野性不改
野性不改 2020-12-21 11:39

We need to add anchors and highlights for some keywords/sentences in the html page. It turns out the highlighting is really slow in Firefox.

In the following code, a

2条回答
  •  礼貌的吻别
    2020-12-21 12:06

    This is my default highlighting snippet and works fine in every browser. Try it out.

    Demo: http://jsbin.com/adeneh/1/edit

    function highlight(text, words, tag) {
    
      // Default tag if no tag is provided
      tag = tag || 'span';
    
      var i, len = words.length, re;
      for (i = 0; i < len; i++) {
        // Global regex to highlight all matches
        re = new RegExp(words[i], 'g');
        if (re.test(text)) {
          text = text.replace(re, '<'+ tag +' class="highlight">$&');
        }
      }
    
      return text;
    }
    
    // Usage:
    var el = document.getElementById('element');
    el.innerHTML = highlight(
      el.innerHTML, 
      ['word1', 'word2', 'phrase one', 'phrase two', ...]
    );
    

    And to unhighlight:

    function unhighlight(text, tag) {
      // Default tag if no tag is provided
      tag = tag || 'span';
      var re = new RegExp('(<'+ tag +'.+?>|<\/'+ tag +'>)', 'g');
      return text.replace(re, '');
    }
    

提交回复
热议问题