请教和正则的问题

首先,javascript中正则的exec方法返回的既然是数组为什么下面代码的length值为1而不是2,

还有就是exec的lastindex属性为什么是undefined???

<!DOCTYPE html>
<html>
    <head>
       <meta charset="utf-8">
       <title>正则表达式</title>
       <style>
           
       </style>
               
    </head>
    <body>
      <script type="text/javascript">
          
          /*var pattem = new RegExp ("box");
          var str = "box";
          alert(pattem.test(str));    */

          /*var pattem = /box/i;
          var str = "Box";
          alert(pattem.test(str));  */

          /*alert(/box/i.test("Box")) */    

          var pattem  = /box/;
          var str = "this is a box,box";
          alert(pattem.exec(str).lastIndex);


      </script>
    </body>
</html>
阅读 2.3k
2 个回答

lastIndex指的是正则对象的属性,并不是exec返回的结果的属性。

var reg = /box/g;
var str = 'this is a box , box ';
while(reg.exec(str))
    console.log(reg.lastIndex);

MDN:
If the match succeeds, the exec() method returns an array and updates properties of the regular expression object. The returned array has the matched text as the first item, and then one item for each capturing parenthesis that matched containing the text that was captured.

你确定你正确理解这些话的意思了?

RegExp.exec返回的是结果数组. 不包含lastIndex这一类的东西. 只有截取的字符串.

lastIndex这一类的在RegExp对象内

var re = /hi/
re.exec('hi')
re.lastIndex // => 0

详细请参阅MDN文档

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题