match 方法
使用正则表达式模式对字符串执行查找,并将包含查找的结果作为数组返回,如果匹配失败,返回null。
str.match(rgExp)
参数:
str 必选项。对其进行查找的 String 对象或字符串文字。
rgExp 必选项。为包含正则表达式模式和可用标志的正则表达式对象。
也可以是包含正则表达式模式和可用标志的变量名或字符串文字。
其余说明与exec一样,不同的是如果match的表达式匹配了全局标记g将出现所有匹配项,而不用循环,但所有匹配中不会包含子匹配项。
例1:
<!DOCTYPE html>
<html>
<head>
<title>MatchDemo</title>
<script type="text/javascript" language="JavaScript">
function MatchDemo(){
var r, re;
var s = "The rain in Spain falls mainly in the plain";
//创建正则表达式模式。 g 代表全部匹配 并且不含子匹配项
re = /(a)in/ig;
// 尝试去匹配搜索字符串,并把匹配结果放到r中
r = s.match(re);
//输出ain,ain,ain,ain
document.write(r);
document.write("<br />");
//匹配第一个,并韩子匹配项
re = /(a)in/i;
// 尝试去匹配搜索字符串,并把匹配结果放到r中
r = s.match(re);
//输出ain,a
document.write(r);
document.write("<br />");
//匹配第一个,并韩子匹配项
re = /(b)in/i;
// 尝试去匹配搜索字符串,并把匹配结果放到r中
r = s.match(re);
//输出null
document.write(r);
}
</script>
</head>
<body onload="MatchDemo()">
</body>
</html>
输出结果:
ain,ain,ain,ain
ain,a
null
转载于:https://blog.51cto.com/chcchb/1329920