var url = 'http://blog.163.com/album?id=1#comment'; var reg = /^(https?:)\/\/([^\/]+)(\/[^\?]*)?(\?[^#]*)?(#.*)?$/; // var reg = /^(https?:)\/\/([^\/]+)([^\?]*)([^#]*)(.*)$///与上面的正则效果相同.;
var arr = url.match(reg);
//arr[0]为原字符串."http://blog.163.com/album?id=1#comment" //对应括号所匹配的字符 var protocol= arr[1]//"http:" var host= arr[2]//"blog.163.com" var pathname= arr[3]//"/album" var search= arr[4]//"?id=1" var hash= arr[5]//"#comment"
替换一个子串:str.replace(regexp/substr,replacement)
第二个参数是字符时
1 2 3 4 5 6
var str = "the price of tomato is 5, the price of apple is 10." str.replace(/(\d+)/,"$1.00") "the price of tomato is 5.00, the price of apple is 10." //使用全局模式 str.replace(/(\d+)/g,"$1.00") "the price of tomato is 5.00, the price of apple is 10.00."
第二个参数是函数时
1 2 3 4 5 6 7 8 9 10 11 12
var html = '<label>网址:</label><input placeholder="以http://起始">'; html = html.replace(/[<>]/g, function(m0){ switch(m0){ case'<': return'<'; case'>': return'>'; } }); //处理后输出结果为: console.log(html);//<label>网址:</label><input placeholder="以http://起始">