js 正则 为url添加http标识

来源:互联网 发布:个人网络炒美元 编辑:程序博客网 时间:2024/05/22 08:05

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

原创粉丝点击