search and replace with jQuery
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">' + $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 alre开发者_开发百科ady linked.
can anyone suggest me, what to do....
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">' + $1 + '</a>');
});
$('body').html(search);
}
});
If you only want to replace on the first instance of "jQuery", remove the g
modifier from your regex.
- Select all text nodes that do not have
<a>
parents. Find the regex in the text nodes only and do the replace
var regex = /jQuery/g; // Get all text nodes: var $textNodes = $("*").contents().filter(function() { return this.nodeType === 3 && $(this).parent("a").length === 0; });
// Iterate through the text nodes, replacing the content // with the link: $textNodes.each(function(index, element) { var contents = $(element).text(); contents = contents.replace(regex, "<a href='http://www.jquery.com'>jQuery</a>"); $(element).replaceWith(contents); });
I do not recommend using the "*" selector, as it will cause performance issues. Replace that selector with something that is more accurate (for example, if you're looking for text inside of <p>, <span>, <div>
, you could write $("p span div")
精彩评论