您的位置:首页 > Web前端 > JavaScript

js中使用正则表达式(g模式和非g模式的区别)

2016-07-12 12:51 633 查看
js中使用正则表达式(g模式和非g模式的区别)

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>mischen</title>
<script>
//js中使用正则表达式
function test(){
//生成正则表达式对象;
// 在g模式下,正则表达式对象的exec和test方法,依赖 正则表达式对象的lastIndex属性,而lastIndex会根据我们exec
// 和test的执行 发生偏移 如果没有相应匹配 lastIndex 重归0
//在非g模式下,正则表达式对象的exec和test方法, lastIndex 不会发生偏移
//exec方法 如果正则表达式中 有分组 第一个返回的是 匹配到的字符串 后面是根据分组分别返回的匹配的 字符串
var reg=new RegExp("\\d+[a-z]+","ig"); //字符串里 \ 表示转译
var str="123abc123def";
alert(reg.lastIndex);//0
alert(reg.exec(str));//123abc
alert(reg.lastIndex);//6
alert(reg.test(str));//true
alert(reg.lastIndex);//12
}
// test();
test1();
function test1(){
//非g模式下使用 exec 和test
var reg=new RegExp("\\d+[a-z]+","i");
var str="123abc123def";
// alert(reg.lastIndex);//0
// alert(reg.exec(str));//123abc
// alert(reg.lastIndex);//0
// alert(reg.test(str));//true
// alert(reg.lastIndex);//0
// alert(reg.exec(str));//123abc
// alert(reg.lastIndex);//0
// alert(reg.test(str));//true
// alert(reg.lastIndex);//0
var reg=new RegExp("(\\d+)([a-z]+)","i");
alert(reg.exec(str));//123abc,123,abc
alert(reg.exec(str));//123abc,123,abc
}
</script>
</head>
<body>

</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: