1

i have the following code:

function getArticleContent() {

    var toPromote = 'example';

    var toReplace = '<a href="/tags/'+toPromote+'">'+toPromote+'</a>';

    var content = $(".a-entry").text();

    if (content.search(toPromote) > -1)
    {           
       $('.a-entry').html($('.a-entry').html().replace(new RegExp(toPromote, "g"), toReplace) );
    }
    else
    {
        //
    }
}
$(document).ready(function() {
    getArticleContent();
});

The code works fine, but if an image, or link has an title or alt attribute equal with the text that i want to replace the html it's broken, because the script put's the link in the alt, or title tag.

Best regards


I am trying to do something like this:

<div id="article">
 <p>Some text here, bla bla.</p>
</div>

After the JS function i want to be:

<div>
    <p>Some text <a href="/tags/here">here</a>, bla bla.</p>
</div>
Adam Lear
  • 38,111
  • 12
  • 81
  • 101
iulian
  • 11
  • 2
  • 1
    There is a reason why they say [you shouldn't mix regex with html](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454). **They Don't Mix Well.** Use the dom parser. – Amarghosh Jul 02 '10 at 12:05

2 Answers2

2

You can do something like this, though there may be a shorter way (text nodes are a very rare occurrence for me):

function getArticleContent() {
  var toPromote = 'example';
  $(".a-entry").contents().filter(function() { return this.nodeType == 3; })
    .each(function() {
      if(this.nodeValue.indexOf(toPromote) > -1)
        $(this).replaceWith(this.nodeValue.replace(new RegExp(toPromote, "g"), 
            function(m) { return '<a href="/tags/'+m+'">'+m+'</a>'; })
        );
    });
}
$(getArticleContent);​

You can try a demo here. This filters for text nodes specifically nodeType == 3, for .each() of those, it loops through, and if the text is there, replaces each match with the corresponding link.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
0

Try using the jQuery .attr() tag to do the replacement on the tag on the href attribute or on the .text() of that is what you wish to change.

Otherwise, it might help to show some markup to see what exactly you want (before/after examples).

.attr('href',yournewstuff);

OR

.text(yournewstuff);
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100