简体   繁体   English

不带<a>标签的正则</a>表达式匹配网址<a>-JS</a>

[英]Regex match url without <a> tag - JS

I am looking for a regex expression in JavaScript for the same use case as this post here: regex matching links without <a> tag 我正在寻找JavaScript的正则表达式,以使用与此帖子相同的用例: 正则表达式匹配没有<a>标记的链接

My goal is to transform a string such as 我的目标是转换一个字符串,例如

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>

To

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>

There are many regex examples for a url, but I am not sure how to add an "and" condition for the url match not being in an <a> tag. url有很多正则表达式示例,但是我不确定如何为<a>标记中没有的url匹配添加“ and”条件。 I have only found examples so far for php or python, but not JS. 到目前为止,我仅发现了针对php或python的示例,但未找到JS。

Thank you! 谢谢!

Instead of using regex, you can test the URL that was supplied to see if it is treated as an external resource. 可以使用提供的URL来查看是否将其视为外部资源,而不是使用正则表达式。 Here, I split the string by whitespace, then tested each part to see if it is a defined 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>`; } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM