为啥是null啊,老师

为啥是null啊,老师

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>正则表达式</title>
</head>

<body>

    <script type="text/javascript">
        var str = 'regular expression = regexp';
        var regexp1 = /lar\sexp/g;
        var regexp2 = new RegExp('lar\\sexp','g');
        console.log(regexp1.test(str));
        console.log(regexp2.test(str));
        console.log(regexp1.exec(str));
        console.log(regexp2.exec(str));
    </script>
</body>

</html>


正在回答 回答被采纳积分+1

登陆购买课程后可参与讨论,去登陆

1回答
好帮手慕星星 2022-09-27 09:40:36

同学你好, 是正则中使用全局g的原因,文档解释如下:

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test

https://img1.sycdn.imooc.com//climg/633254160983485c08570147.jpg

有两种接解决方式:

1、去掉全局g

https://img1.sycdn.imooc.com//climg/6332544109d3c31306890227.jpg

https://img1.sycdn.imooc.com//climg/633254460985a8c407890124.jpg

2、重置lastIndex值为0

https://img1.sycdn.imooc.com//climg/6332548709b8f52505680230.jpg

https://img1.sycdn.imooc.com//climg/6332548e0945b39b07280108.jpg

祝学习愉快!

问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师