Jquery and RegExp

I am creating a function, replace a keyword in HTML with a link. The problem is that when a keyword is in a link, it replaces it.

$(document).ready( function () {
    $("#content").highlight( "example", "<a href=\"http://www.example.com\">$1</a>" );});

jQuery.fn.highlight = function (text, o) {
return this.each( function(){
    var replace = o;
    $(this).html( $(this).html().replace( new RegExp('('+text+'(?![\\w\\s?&.\\/;#~%"=-]*>))', "ig"), replace) );
});}

      

and my HTML

<div id="content">
    <h2>the word "example" replaced by the link</h2>
    <p>this is an example</p>

    <p>this is an example number 2</p>
    <p><a href="http://www.wrong.com">this is an example</a></p>
</div>

      

0


a source to share


1 answer


I would check each element of the loop to see if it is an anchor tag before doing the replacement.



if( !$(this).is('a') ) {
  // Replace Code here
}

      

+1


a source







All Articles