此字符串:
“https://stackoverflow.com/1 test https://stackoverflow.com/2
”应转换为:
“<a href="https://stackoverflow.com/1> stackoverflow.com/1 </a> test <a href="https://stackoverflow.com/2"> stackoverflow.com/2 </a>
”
那么需要改变的是:
<a href>..</a>
放在链接周围,以便点击它。到目前为止我所拥有的:
AngularJS
$scope.convertedBio = function(value) {
var text = value.replace(/(http[^\s]+)/, '<a href="$1">$1</a>');
return text;
}
但是,这会返回“<a href="https://stackoverflow.com/1">https://stackoverflow.com/1</a> test https://stackoverflow.com/2
”
答案 0 :(得分:0)
你需要:
将除协议部分和可选www.
之外的整个网址捕获到其他组
将此群组的值用作<a>
的文字
添加全局修饰符
var text = value.replace(/(https?:\/\/(?:www\.)?([^\s]+))/g, '<a href="$1">$2</a>');
^ ^ ^ ^
1 1 3 2
答案 1 :(得分:0)
function replaceUrls(value) {
var text = value.replace(/(https?:\/\/)(www\.)?([\S]*)/g, '<a href="$1$2$3">$3</a>');
return text;
}
var x = replaceUrls('http://stackoverflow.com/1 test https://www.stackoverflow.com/2')
console.log(x)
// output <a href="https://stackoverflow.com/1">stackoverflow.com/1</a> test <a href="https://www.stackoverflow.com/2">stackoverflow.com/2</a>