views:

45

answers:

3

Hi, 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

A: 

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
A: 

I am trying to do something like this: `

Some text here, bla bla.

`

After the JS function i want to be:

<div>
<p>Some text <a href="/tags/here">here</a>, bla bla.</p> </div>

iulian
+2  A: 

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
+1 - i like the use of contents, filter and nodeType. Very good answer.
Krunal
The script works but it the get from the BD the article details whit tags, for example:<div id="test"><p>My text here...</p></div>
iulian
@iulian - Here's an updated example, give it a try: http://jsfiddle.net/7C9DC/2/
Nick Craver
@Nick Thx but still not working, i think i will take a rest, and try latter, thx for the answers :)
iulian
@iulian - Here is a version with your exact example: http://jsfiddle.net/7C9DC/3/
Nick Craver