如何檢測(cè) JavaScript 字符串中的 URL 并將其轉(zhuǎn)換為鏈接?
有時(shí),我們必須在 JavaScript 字符串中查找 URL。
在本文中,我們將了解如何在 JavaScript 字符串中查找 URL 并將它們轉(zhuǎn)換為鏈接。
我們可以創(chuàng)建自己的函數(shù),使用正則表達(dá)式來(lái)查找 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 。
然后我們查找斜杠和文本。
正則表達(dá)式末尾的 g 標(biāo)志讓我們可以搜索字符串中的所有 URL。
然后我們用 urlRegex 調(diào)用 text.replace 并在回調(diào)中返回一個(gè)帶有匹配 url 的字符串。
因此,當(dāng)我們用 text 調(diào)用 urlify 時(shí),我們得到:
- 'Find me at <a href="http://www.example.com>http://www.example.com</a> and also at <a href="http://stackoverflow.com>http://stackoverflow.com</a>'
我們可以使用更復(fù)雜的正則表達(dá)式使 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。
我們還在模式中包含 : 、字母、與號(hào)和下劃線。