javascript 正則表達式基礎
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://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>
最後更新:2017-04-03 18:51:47