一、RegExp对象方法:
1.exec() 检索字符串中指定的值,并返回值(找不到返回null)
效果:
<textarea name="content" id="content" cols="20" rows="10"></textarea><input type="button" onclick="regTest()" value="查找"> <script type="text/javascript"> function regTest(){ var content = document.getElementById("content").value; var regExp = /(\d){4}/gi; while(res = regExp.exec(content)){ console.log("找到"+res[0]); } } </script>
2.test() 检索字符串中指定值,返回true或false
效果:
<textarea name="content" id="content" cols="20" rows="10"></textarea><input type="button" onclick="regTest()" value="查找"> <script type="text/javascript"> function regTest(){ var content = document.getElementById("content").value; var regExp = /(\d){4}/gi; if(regExp.test(content)){ console.log("找到了"); } } </script>
3.属性
index、leftContext 、rightContext
<script type="text/javascript"> var str= "abcd4564hui454s0ss4894d7937asda"; var myreg = /(\d){4}/gi; while(res = myreg.exec(str)){ console.log("index="+RegExp.index + " leftContext="+RegExp.leftContext+" rightContext="+RegExp.rightContext) } </script>
在chrome中的效果:(index属性在chrome,firefox,opera中都是不支持的)
在ie中的效果:
二、String类型对象的正则表达式用法
1.search
返回所要找的元素在字符串中的位置
var str= "abcdhuisd";
console.log(str.search(/dhu/));
返回:3
2.match 可以在字符串内检索指定的值,或找到一个或多个正则表达式的匹配,返回的是指定的值,是一个数组
<script type="text/javascript"> var str= "abcd4564hui454s0ss4894d7937asda"; var myreg = /(\d){4}/gi; res = str.match(myreg); for(var i = 0;i<res.length;i++){ console.log(res[i]); } </script>
3.replace 正则替换
<script type="text/javascript"> var str= "abcd4564hui454s0ss4894d7937asda"; var myreg = /(\d){4}/gi; res = str.replace(myreg,"四个数字"); console.log(res); </script>
4.split 分割成数组:
<script type="text/javascript"> var str= "abcd4564hui454s0ss4894d7937asda"; var myreg = /(\d){4}/gi; res = str.split(myreg); console.log(res); </script>
或者:
<script type="text/javascript"> var str= "abcd4564hui454s0ss4894d7937asda"; var myreg = /(\d){4}/gi; res = str.split(""); console.log(res); </script>
3.例题:
在一个子串中找到一个四位数,第一位和第四位相等,第二位和第三位相等,如1221
<script type="text/javascript"> var str= "abcd4564hui5665ss8899d7937asda"; var myreg = /(\d)(\d)\2\1/gi; while(res = myreg.exec(str)){ console.log(res[0]) } </script>
找到一个字串中如aabbccdd的子串
<script type="text/javascript"> var str= "abcd4564hui11223344ss8899d7937asda"; var myreg = /(\d)\1(\d)\2(\d)\3(\d)\4/gi; while(res = myreg.exec(str)){ console.log(res[0]) } </script>