我正在尝试包装某些文本中的任何 url 并将其转换为超链接......但我不想包装已经被超链接包装的 url。
例如:
<a href="http://twitter.com">Go To Twitter</a>
here is a url http://anotherurl.com
以下代码:
function replaceURLWithHTMLLinks(text) {
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
return text.replace(exp, "<a href='$1'>$1</a>");
}
给出以下输出:
<a href="<a href='http://twitter.com/twitter'>http://twitter.com/twitter</a>">@BIR</a>
<a href="http://anotherurl.com">http://anotherurl.com</a>
如何修改正则表达式以排除已经超链接的网址?
谢谢
回答:
新方法是:
function replaceURLWithHTMLLinks(text) {
var exp = /(?:^|[^"'])((ftp|http|https|file):\/\/[\S]+(\b|$))/gi
return text.replace(exp, " <a href='$1'>$1</a>");
}
上述代码按要求运行。我从评论中的链接修改了正则表达式,因为它包含一个错误,其中包含句号,它现在排除了完整 url 之后的任何句号。