我目前正在使用以下代码,在页面上搜索URL的div并将其替换为标记。
但是当我们在div中有一个embed标签时,它会弄乱这些标签中的链接。
function replaceURLWithHTMLLinks(text) {
return text.replace(/(ftp|http|https|file):\/\/[\S]+(\b|$)/gim,'<a href="$&" class="my_link" target="_blank">$&</a>').replace(/([^\/])(www[^ <]+(\b|$))/gim,'$1<a href="http://$2" class="my_link" target="_blank">$2</a>');
}
$(document).ready(function(){
var htmlStr = $("div.content-a").html();
var htmlStrAfter = replaceURLWithHTMLLinks(htmlStr);
$("div.content-a").html(htmlStrAfter);
});
任何人都可以告诉我们如何排除任何以“或”开头的http:// ...?
或者类似的?
答案 0 :(得分:3)
您可能应该按照建议使用DOM。但为了使您的正则表达式按预期工作,您应该使用(?:^|[^"'])
作为前缀。这意味着匹配行的开头或匹配除'
和"
之外的任何字符。因此,您的第一个正则表达式将如下所示:
/(?:^|[^"'])(ftp|http|https|file):\/\/[\S]+(\b|$)/gim
你对replace
方法的链接很难看。如果将方法调用拆分为不同的行,代码将更具可读性。
更新:为了跳过第一个多余字符,您可以使用$1
代替$&
,并且必须将正则表达式更改为:
/(?:^|[^"'])((ftp|http|https|file):\/\/[\S]+(\b|$))/gim
答案 1 :(得分:0)
+1约翰内斯说的......
$(document).ready(function(){
$('div.content').contents().filter(function() {
return this.nodeType == 3;
}).each(function(){
this.nodeValue.replace(/(ftp|http|https|file):\/\/[\S]+(\b|$)/gim,'<a href="$&" class="my_link" target="_blank">$&</a>').replace(/([^\/])(www[^ <]+(\b|$))/gim,'$1<a href="http://$2" class="my_link" target="_blank">$2</a>');
});
});
请注意,上面的代码未经测试,但它应该看起来像我认为的那样。