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

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>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值