自己试验了一下exec和match的异同
下面列出测试一个用于获得url地址信息的方法的代码:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>exec.html</title>
<meta http-equiv="content-type" content="text/html; charset=gb2312">
</head>
<body>
<script type="text/javascript">
var url = "http://www.baidu.com/abc.jsp?method=method&name=abc&age=12";
var patt=/[?&](\w+?)=([^&]*)/;
var pattGlobal=/[?&](\w+?)=([^&]*)/g;
console.group("单个匹配")
console.log("exec返回的信息:%o",patt.exec(url));
console.log("match返回的信息:%o",url.match(patt));
console.groupEnd("单个匹配");
var execArr = [];
var o = pattGlobal.exec(url);
while(o){
execArr.push(o);
o = pattGlobal.exec(url);
}
var match = url.match(pattGlobal);
console.group("全局匹配")
console.log("exec返回的信息:%o",execArr);
console.log("match返回的信息:%o",match);
console.groupEnd("全局匹配");
</script>
</body>
</html>
在firefox中控制面板输出:
总结:
1、单个匹配的时候,match和exec返回的信息是一样的
2、全局匹配的时候,match会返回匹配的字符串数组,而exec则返回多个单个匹配结果,exec匹配获得信息详细得多。
3、全局匹配的时候,如果需要exec重新匹配字符串,需要pattGlobal.lastIndex=0。