今天逛 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>
帖子地址: