javascript 正则表达式基础
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Javascript 正则表达式基础</title>
</head>
<body>
1.使用RegExp对象:<br />
①test()方法:用于判定是否匹配。<br />
②exec()方法:返回一个数组,数组中的第一个条目是第一个匹配,其他则是反向引用。<br />
③string.match()方法:返回字符串中所有匹配条目组成的数组。<br />
2.扩展字符串方法:<br />
①replace()方法:示例正则替换。<br />
②split()方法:示例正则分割。<br />
<script type="text/javascript">
var toMatch = "a bat,a cat,a Cat,a fAt baT,a faT cat";
var regx = /cat/;
alert("1.test():" + regx.test(toMatch));
alert("2.exec():" + regx.exec(toMatch).length);
var matchRegx = /at/gi;
var matches = toMatch.match(matchRegx);
alert("3.string.match():" + matches.length);
var toReplace = "the sky is red";
alert("4.普通replace():" + toReplace.replace("red", "blue"));
var replaceRegx = /red/; //注意:如果需要替换所有"red",需指明正则表达式为:/red/g
alert("5.正则replace()1:" + toReplace.replace(replaceRegx, "blue"));
var replaceResult = toReplace.replace(replaceRegx, function (matched) { return "blue" });
alert("5.正则replace()2:" + replaceResult);
var colorStr = "red,blue,yellow,green";
var splitReg = /\,/; //注意元字符需转义
var colorArr = colorStr.split(splitReg);
alert("6.正则split():" + colorArr.length);
</script>
</body>
</html>