js 正則 為url添加http標識

來源:互聯網
上載者:User

今天逛 stackoverflow 時,看到這樣一個問題:

有這樣一個JS 字串:

http://www.google.comwww.google.comcode.google.comhttp://code.google.com/hosting/search?q=label%3aPython

需要為沒有http頭的URL添加http,有的保持不變。結果如下:

1: http://www.google.com2: http://www.google.com3: http://code.google.com4: http://code.google.com/hosting/search?q=label%3aPython

看到這個問題,首先我想到在.NET正則裡很好實現,大體思路如下:

void Main(){string html=@"http://www.google.comwww.google.comcode.google.comhttp://code.google.com/hosting/search?q=label%3aPython";        html=Regex.Replace(html,@"(?i)(https?://)?(\w+\.?)+(\/[a-zA-Z0-9\?%=_\-\+\/]+)?",  m=>m.Groups[1].Success?m.Value:"http://"+m.Value);  Console.WriteLine(html);/*http://www.google.comhttp://www.google.comhttp://code.google.comhttp://code.google.com/hosting/search?q=label%3aPython*/}

好久沒寫js代碼,稍稍考慮了一會,按照.NET的思路,想到以下解決方案,在此記錄一下,希望以後能用的上。

<!DOCTYPE html><html lang="en" xmlns="http://www.w3.org/1999/xhtml"><head>    <meta charset="utf-8" />    <title></title>    <script>        var html = 'http://www.google.com';        html += '\rwww.google.com';        html += '\rcode.google.com';        html += '\rhttp://code.google.com/hosting/search?q=label%3aPython';        var regex = /(https?:\/\/)?(\w+\.?)+(\/[a-zA-Z0-9\?%=_\-\+\/]+)?/gi;        alert('before replace:');        alert(html);        html = html.replace(regex, function (match, capture) {            if (capture) {                return match            }            else {                return 'http://' + match;            }        });        alert('after replace:');        alert(html);    </script></head><body></body></html>

文章地址:

http://stackoverflow.com/questions/17689999/bulletproof-url-matching-regex-for-javascript/17690463#17690463

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.