mark text in a string with regular expression but exclude links

后端 未结 2 1210
清歌不尽
清歌不尽 2021-01-28 03:23

I have a text and I want when a user search for a term, the term becomes highlighted by wrapping the term with mark tag.

javascript to wrap the match term:



        
相关标签:
2条回答
  • 2021-01-28 04:00
    1. You're reinverting the wheel
    2. Using innerHTML will destroy events
    3. Using innerHTML will trigger regeneration of the DOM

    To make thins easy you should use an existing plugin. There are many jQuery plugins out there, but as you haven't added the jquery tag I assume that you're searching a plain JS solution. Then the only plugin is mark.js.

    Example of your use case

    0 讨论(0)
  • 2021-01-28 04:05

    Use a negative lookahead to add an additional constraint that the term is not followed by a > without first having a <. This will effectively exclude matches within <...> markup.

    var pattern = new RegExp('('+term+')(?![^<]*>)', 'gi');
    

    https://jsfiddle.net/qdk80o0k/

    0 讨论(0)
提交回复
热议问题