如何檢測 JavaScript 字符串中的 URL 并將其轉換為鏈接?

有時,我們必須在 JavaScript 字符串中查找 URL。
在本文中,我們將了解如何在 JavaScript 字符串中查找 URL 并將它們轉換為鏈接。
我們可以創(chuàng)建自己的函數(shù),使用正則表達式來查找 URL。
例如,我們可以這樣寫:
const urlify = (text) => {
const urlRegex = /(https?:\/\/[^\s]+)/g;
return text.replace(urlRegex, (url) => {
return `<a href="${url}>${url}</a>`;
})
}
const text = 'Find me at http://www.example.com and also at http://stackoverflow.com';
const html = urlify(text);
console.log(html)
我們創(chuàng)建了接受 text 字符串的 urlify 函數(shù)。
在函數(shù)中,我們優(yōu)化了 urlRegex 變量,該變量具有用于匹配url的regex。
我們檢查 http 或 https 。
然后我們查找斜杠和文本。
正則表達式末尾的 g 標志讓我們可以搜索字符串中的所有 URL。
然后我們用 urlRegex 調用 text.replace 并在回調中返回一個帶有匹配 url 的字符串。
因此,當我們用 text 調用 urlify 時,我們得到:
'Find me at <a href="http://www.example.com>http://www.example.com</a> and also at <a
我們可以使用更復雜的正則表達式使 URL 搜索更精確。
例如,我們可以這樣寫:
const urlify = (text) => {
const urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
return text.replace(urlRegex, (url) => {
return `<a href="${url}>${url}</a>`;
})
}
const text = 'Find me at http://www.example.com and also at http://stackoverflow.com';
const html = urlify(text);
console.log(html)
我們搜索 http、https、ftp 和文件url。
我們還在模式中包含 : 、字母、與號和下劃線。
最近文章
開發(fā)App新選擇:使用 Vue Native 構建移動應用 5 個可以加速開發(fā)的 VueUse 庫函數(shù) Vue 中使用defineAsyncComponent 延遲加載組件 使用React Native可以開發(fā)Window桌面應用了! 黑客說:如何做到 4 天上線一個小程序? Pinia與Vuex的對比:Pinia是Vuex的良好替代品嗎? 2021年加速App開發(fā)的8個最佳跨平臺框架
評論
圖片
表情
