<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

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

          共 1573字,需瀏覽 4分鐘

           ·

          2021-08-22 11:43

          有時,我們必須在 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。

          我們檢查 httphttps

          然后我們查找斜杠和文本。

          正則表達式末尾的 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)

          我們搜索 httphttps、ftp 和文件url。

          我們還在模式中包含 : 、字母、與號和下劃線。


          最近文章

          瀏覽 48
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  亚洲操B在线看 | 黄色日本在线观看视频 | 久久1122精品少妇 | a线视频免费观看:中文字幕 | 青青草视频两男一女在线看 |