views:

73

answers:

2

Hi,

I want to search a keyword into body and replace it with a link if it is already not linked to somewhere. My code is :

var search = $('body').html();
search = search.replace(/jQuery/g, function($1){
    return('<a href="http://jquery.com"&gt;' + $1 + '</a>');
});

$('body').html(search);

The problem is, it replaces all keyword even if it is already linked.

I dont want to replace if it is already linked.

can anyone suggest me, what to do....

A: 

The problem is, it replaces all keyword even if it is already linked.

So you mean if I have a link currently in the page containing the search term that is being searched, it is replaced? If so, (I'm not good with regexp's), try adding something that makes sure there is not an "http://" or something similar before the string you are looking for.

JamWaffles
A: 

You should use jQuery selectors to search for links.

$(document).ready(function() {
    var links, search;

    $links = $('a[href=http://jquery.com]');

    if ($links.length) {
        search = $('body').html().replace(/jQuery/g, function($1){
            return('<a href="http://jquery.com"&gt;' + $1 + '</a>');
        });

        $('body').html(search);
    }
});

If you only want to replace on the first instance of "jQuery", remove the g modifier from your regex.

lonesomeday
The entire point of the question is that these strings are NOT in links. - OP wants to search the HTML and replace `blah` with `<a href="...">blah</a>` and also leave all `blah` s that are already in links untouched.
Peter Ajtai
Ah, I was reading it as he wanted to create links only if there wasn't already a link anywhere on the page. What you say makes much more sense.
lonesomeday