live highlight a word(s) with jQuery

本秂侑毒 提交于 2019-12-06 08:10:28

The issue is that after the first successful replace the pattern now has to also match the ending span tag that has been inserted after the first matched character.

The HTML looks like this after entering "l":

<p><span class="highlight">l</span>orem ip sum</p>

"lorem" will no longer match because of the span.

Now with solution:

Here is a fix that should get it doing what you want:

$('#' + id).each(function() {
    $('span.highlight',this).replaceWith($('span.highlight',this).text()); // Fix

    var content = $(this).html();

    if (!content) return;
    $(this).html(content.replace(pattern, o.template));
});

Assuming that you will only have a single highlight span, the line below removes the span and replaces it with the text that it contained. Then the replace happens as normal.

$('span.highlight',this).replaceWith($('span.highlight',this).text()

A working example is here: http://jsfiddle.net/ryanrolds/N4DCR/

You should specify the global flag for your regular expression even if you are in case-sensitive mode. This is probably why only the first char gets replaced. Try using this:

pattern = new RegExp('(>[^<.]*)(' + o.words + ')([^<.]*)', (o.caseSensitive ? "" : "i") + "g");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!