gpt4 book ai didi

javascript - 如何替换不在 javascript 中的 href 标记内的 URL

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:26:21 28 4
gpt4 key购买 nike

我有一种情况,我的文本包含 URL 链接。链接有两种形式

  1. www.stackoverflow.com
  2. 堆栈溢出

我正在尝试创建一个使用正则表达式的简单函数,它将所有 1 类型的链接都用 A HREF 标记包装起来,但让其他链接单独包装。

我有这样的东西,但没有成功。

function replaceURLWithHTMLLinks(text) {
var exp = /(<(\s*)a(\s)*href.*>.*<\/(\s)*a(\s*)>)/ig;
var matches = exp.exec(text);
for(var i=0; i < matches.length; i++) {
var line = matches[i];
if(!exp.test(line)) {
var exp2 = /(\b(?:(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[-A-Z0-9+&@#\/%=~_|$])|”(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)[^"\r\n]+”?|’(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)[^'\r\n]+’?)/ig;
text = text.replace("http://","");
text = text.replace(exp2, "<a href=http://$1>$1</a>");
}
}

return text;
}

它不工作但希望有人能修复它:)

编辑

修复它的解决方案,在@MikeM 回答的帮助下

function replaceLinksSO(text) {
rex = /(<a href=")?(?:https?:\/\/)?(?:(?:www)[-A-Za-z0-9+&@#\/%?=~_|$!:,.;]+\.)+[-A-Za-z0-9+&@#\/%?=~_|$!:,.;]+/ig;
return text.replace(rex, function ( $0, $1 ) {
if(/^https?:\/\/.+/i.test($0)) {
return $1 ? $0: '<a href="'+$0+'">'+$0+'</a>';
}
else {
return $1 ? $0: '<a href="http://'+$0+'">'+$0+'</a>';
}
});
}

最佳答案

在不尝试分析上面复杂的正则表达式和函数的情况下,这里是一个使用玩具 url 匹配模式来说明进行此类替换的方法的示例实现

var str = ' www.stackoverflow.com  <a href="http://www.somesite.com">somesite</a> www.othersite.org '
rex = /(<a href=")?(?:https?:\/\/)?(?:\w+\.)+\w+/g;

str = str.replace( rex, function ( $0, $1 ) {
return $1 ? $0 : '<a href="' + $0 + '">' + $0 + '</a>';
});

您可以更改 url 匹配模式并插入例如\s* 根据需要。

关于javascript - 如何替换不在 javascript 中的 href 标记内的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14999119/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com