mark text in a string with regular expression but exclude links

后端 未结 2 1208
清歌不尽
清歌不尽 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: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/

提交回复
热议问题