Javascript Regex 用链接替换 URL,但不在 embed(或 img)标签中 [英] Javascript Regex to replace URLs with links, but not in embed (or img) tags
问题描述
我目前正在使用以下代码,在页面上的 div 中搜索 URL 并将其替换为标签.
I'm currently using the following code, to search the a div on a page for URLs and replace them with a tags.
然而,当我们在 div 中嵌入标签时,它会弄乱这些标签中的链接.
However when we have a embed tags within the div it messes up the links within these tags.
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);
});
谁能告诉 be 如何排除任何以 " 或 ' 开头的 http://... ?
Can anyone tell be how to perhaps exclude any http://... that are preceded by a " or ' ?
或者类似的?
推荐答案
或许,你应该按照推荐使用 DOM.但是为了使您的正则表达式按预期工作,您应该在它前面加上 (?:^|[^"'])
.这意味着匹配行首或匹配除 ' 之外的任何字符
和 "
.因此,您的第一个正则表达式将如下所示:
Probably, you should use DOM as recommended. But in order to make your regexp work as desired, you should prepend it with (?:^|[^"'])
. That means match start of line or match any character excepting '
and "
. So first of your regexps will look as follows:
/(?:^|[^"'])(ftp|http|https|file):\/\/[\S]+(\b|$)/gim
并且您的 replace
方法链很丑陋.如果您将方法调用拆分为不同的行,代码将更具可读性.
And your chaining of replace
method is ugly. Code will be much more readable if you will split method invocations to different lines.
更新:为了跳过第一个多余的字符,您可以使用 $1
而不是 $&
并且您的正则表达式必须更改为:
Update: And in order to skip first excess character you can use $1
instead of $&
and your regexp must be changed to this:
/(?:^|[^"'])((ftp|http|https|file):\/\/[\S]+(\b|$))/gim
这篇关于Javascript Regex 用链接替换 URL,但不在 embed(或 img)标签中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!