js 正则 为url添加http标识

今天逛 stackoverflow 时,看到这样一个问题:


有这样一个JS 字符串:

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

需要为没有http头的URL添加http,有的保持不变。结果如下:

1: http://www.google.com
2: http://www.google.com
3: http://code.google.com
4: http://code.google.com/hosting/search?q=label%3aPython

看到这个问题,首先我想到在.NET正则里很好实现,大体思路如下:


void Main()
{
	string html=@"http://www.google.com
www.google.com
code.google.com
http://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.com
	http://www.google.com
	http://code.google.com
	http://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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值