How to highlight text using javascript

后端 未结 13 2543
名媛妹妹
名媛妹妹 2020-11-22 02:32

Can someone help me with a javascript function that can highlight text on a web page. And the requirement is to - highlight only once, not like highlight all occurrences of

13条回答
  •  一个人的身影
    2020-11-22 02:54

    I have the same problem, a bunch of text comes in through a xmlhttp request. This text is html formatted. I need to highlight every occurrence.

    str=''
        +'

    some text containing fox.

    '

    The problem is that I don't need to highlight text in tags. For example I need to highlight fox:

    Now I can replace it with:

    var word="fox";
    word="(\\b"+ 
        word.replace(/([{}()[\]\\.?*+^$|=!:~-])/g, "\\$1")
            + "\\b)";
    var r = new RegExp(word,"igm");
    str.replace(r,"$1")
    

    To answer your question: you can leave out the g in regexp options and only first occurrence will be replaced but this is still the one in the img src property and destroys the image tag:

    '
        +'

    some text containing fox.

    ' var word="fox"; word="(\\b"+ word.replace(/([{}()[\]\\.?*+^$|=!:~-])/g, "\\$1") + "\\b)"; var r = new RegExp(word,"igm"); str.replace(/(>[^<]+<)/igm,function(a){ return a.replace(r,"$1"); });

提交回复
热议问题