今天逛 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