Javascript RegExp教程

JavaScript RegExp lastIndex

说明

lastIndex RegExp 对象的读/写属性。对于设置了"g"属性的正则表达式,它包含一个整数,用于指定紧跟 RegExp.exec()RegExp.test()找到的最后一个匹配项之后的字符位置 方法。这些方法使用此属性作为它们进行下一次搜索的起点。
此属性允许您重复调用这些方法,循环遍历字符串中的所有匹配项,并且仅在设置了"g"修饰符时才起作用。
此属性是读/写的,因此您可以随时设置它以指定下一次搜索应在目标字符串中的哪个位置开始。 exec()test() 在找不到匹配项(或其他匹配项)时自动将 lastIndex 重置为 0。

语法

其语法如下-
RegExpObject.lastIndex

返回值

返回一个整数,指定紧跟在最后一次匹配之后的字符位置。

示例

<html>
   <head>
      <title>JavaScript RegExp lastIndex Property</title>
   </head>
   
   <body>      
      <script type = "text/javascript">
         var str = "Javascript is an interesting scripting language";
         var re = new RegExp( "script", "g" );
         
         re.test(str);
         document.write("Test 1-Current Index: " +  re.lastIndex); 
         
         re.test(str);
         document.write("<br />Test 2-Current Index: " + re.lastIndex); 
      </script>      
   </body>
</html>

输出

Test 1-Current Index: 10
Test 2-Current Index: 35 
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4