我一直试图找出用a href
替换纯文本网址的最聪明(也是最有效)的方法,并以某种方式涉及encodeURIComponent()
功能。
到目前为止,我提出的代码如下所示:
var regex = /(\b((https?):\/\/|(www))[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|]*)/ig;
$(element).replaceWith(element.textContent.replace(regex, '<a href="$1" target="_blank">$1</a>'));
现在我想弄清楚在结果上使用encodeURIComponent()
的最佳方法(但仍然只在a href
上,应该保留可见链接而不进行更改)。
输入
1. My website at http://example.com/ is awesome
2. My website at www.example.com is awesome
预期输出:
1. My website at <a href="http%3A%2F%2Fexample.com%2F">http://example.com/</a> is awesome.
2. My website at <a href="www.example.com">www.example.com</a> is awesome.
这是最好的方法吗?
答案 0 :(得分:1)
使用String#replace
回调。匹配可以在回调函数中使用,对于href
属性,可以使用encodeURIComponent
。
var str = `1. My website at http://example.com/ is awesome
2. My website at www.example.com is awesome`;
var regex = /(\b((https?):\/\/|(www))[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|]*)/ig;
str = str.replace(regex, function(m, e) {
return '<a href="' + encodeURIComponent(e) + '" target="_blank">' + e + '</a>';
});
console.log(str);
document.body.innerHTML = str;
&#13;
答案 1 :(得分:0)
您可以使用Group-Operators:
搜索
^(.*)(http:\/\/|www\.)([^\s]*)(.*)$
并替换为
$1<a href="$2$3">$2$3</a> is awesome.
See https://regex101.com/r/mT5hQ4/1
var re = /^(.*)(http:\/\/|www\.)([^\s]*)(.*)$/mg;
var str = '1. My website at http://example.com/ is awesome\n2. My website at www.example.com is awesome';
var subst = '$1<a href="$2$3">$2$3</a> is awesome.';
var result = str.replace(re, subst);
通过此功能,您可以轻松添加encodeURIComponent()