简体   繁体   中英

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

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. I have only found examples so far for php or python, but not 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. Here, I split the string by whitespace, then tested each part to see if it is a defined 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>`; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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