I am looking for a regex expression in JavaScript for the same use case as this post here: regex matching links without <a> tag
的正则表达式匹配网址我的目标是转换诸如这样的字符串
Here is a link https://www.somewebsite.com/ here is a link already in an a tag <a href="https://www.somewebsite.com/">https://www.somewebsite.com/</a>
收件人
Here is a link <a href="https://www.somewebsite.com/">https://www.somewebsite.com/</a> here is a link already in an a tag <a href="https://www.somewebsite.com/">https://www.somewebsite.com/</a>
有许多用于url的正则表达式示例,但是我不确定如何为不在<a>
标记中的url匹配添加“和”条件。到目前为止,我只发现了php或python的示例,而JS没有。
谢谢!
答案 0 :(得分:2)
您可以测试提供的URL来查看它是否被视为外部资源,而不是使用正则表达式。在这里,我用空格分割字符串,然后测试每个部分是否是已定义的URL。
const string = `Here is a link https://www.somewebsite.com/ here is a link already in an a tag <a href="https://www.somewebsite.com/">https://www.somewebsite.com/</a>`;
const newString = string
.split(/\s+/)
.map(string => (isDefinedUrl(string)) ? makeUrl(string) : string)
.join(' ');
console.log(newString);
function isDefinedUrl(possibleUrl) {
const a = document.createElement('a');
a.href = possibleUrl;
return (possibleUrl === a.href);
}
function makeUrl(url) {
return `<a href="${url}">${url}</a>`;
}