0

I build a function thar replace a keyword in the HTML to a link. The problem is that when the keyword is in a link then it will replaced 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>
1
  • I don't know jQuery's .html method, but this looks like another attempt to parse HTML with regular expressions. Commented May 12, 2009 at 13:36

1 Answer 1

1

I would check each element in the loop to see if it's a anchor tag before doing the replace.

if( !$(this).is('a') ) {
  // Replace Code here
}
Sign up to request clarification or add additional context in comments.

1 Comment

i don't go over the text in a loop. i replace it with the replace function, so i cant check every replace.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.