Javascript 搜索并替换为jQuery
我想在正文中搜索一个关键字,如果它还没有链接到某个地方,就用链接替换它。我的代码是:Javascript 搜索并替换为jQuery,javascript,jquery,jquery-plugins,Javascript,Jquery,Jquery Plugins,我想在正文中搜索一个关键字,如果它还没有链接到某个地方,就用链接替换它。我的代码是: var search = $('body').html(); search = search.replace(/jQuery/g, function($1){ return('<a href="http://jquery.com">' + $1 + '</a>'); }); $('body').html(search); 问题是,即使已经链接,它也会替换所有关键字 如果已经链
var search = $('body').html();
search = search.replace(/jQuery/g, function($1){
return('<a href="http://jquery.com">' + $1 + '</a>');
});
$('body').html(search);
问题是,即使已经链接,它也会替换所有关键字
如果已经链接,我不想替换
有谁能给我建议,怎么做……你应该使用jQuery选择器来搜索链接
$(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);
}
});
如果只想替换jQuery的第一个实例,请从正则表达式中删除g修饰符。您应该使用jQuery选择器搜索链接
$(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);
}
});
如果只想替换jQuery的第一个实例,请从正则表达式中删除g修饰符
选择所有没有父节点的文本节点。
仅在文本节点中查找正则表达式并进行替换
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);
});
我不建议使用*选择器,因为它会导致性能问题。将该选择器替换为更精确的选择器,例如,如果要查找中的文本,可以编写$p span div
选择所有没有父节点的文本节点。
仅在文本节点中查找正则表达式并进行替换
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);
});
我不建议使用*选择器,因为它会导致性能问题。将该选择器替换为更精确的选择器。例如,如果您正在查找中的文本,您可以编写$p span div使用解析器而不是RegEx使用解析器而不是RegEx。问题的关键是这些字符串不在链接中。-OP希望搜索HTML并用替换blah,同时保留链接中已经存在的所有blah。啊,我正在阅读它,因为他只想在页面上没有链接的情况下创建链接。你说的更有意义。问题的关键是这些字符串不在链接中。-OP希望搜索HTML并用替换blah,同时保留链接中已经存在的所有blah。啊,我正在阅读它,因为他只想在页面上没有链接的情况下创建链接。你说的更有道理。