簡體   English   中英

不帶<a>標簽的正則</a>表達式匹配網址<a>-JS</a>

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

我正在尋找JavaScript的正則表達式,以使用與此帖子相同的用例: 正則表達式匹配沒有<a>標記的鏈接

我的目標是轉換一個字符串,例如

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匹配添加“ and”條件。 到目前為止,我僅發現了針對php或python的示例,但未找到JS。

謝謝!

可以使用提供的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