首页 > 其他 > 详细

正则的lastIndex 属性

时间:2019-07-30 17:08:37      阅读:112      评论:0      收藏:0      [点我收藏+]

 

简介:正则的lastIndex 属性用于规定下次匹配的起始位置。

注意: 该属性只有设置标志 g 才能使用。

上次匹配的结果是由方法 RegExp.exec() 和 RegExp.test() 找到的,它们都以 lastIndex 属性所指的位置作为下次检索的起始点。这样,就可以通过反复调用这两个方法来遍历一个字符串中的所有匹配文本。

注意:该属性是可读可写的。只要目标字符串的下一次搜索开始,就可以对它进行设置。当方法 exec() 或 test() 再也找不到可以匹配的文本时,它们会自动把 lastIndex 属性重置为 0。

  例子一:在字符串中全局试试子字符串 "ain" , 并输出匹配完成之后的 lastIndex 属性:

var str="The rain in Spain stays mainly in the plain";
var patt1=/ain/g;

while (patt1.test(str)==true) 
{
    document.write("‘ain‘ found. Index now at: "+patt1.lastIndex);
    document.write("<br>");
};

技术分享图片

  例子二:多次检索,打印出lastIndex的位置,当检索到最后没有检索出符合的就从头开始检索

var str="The rain in Spain stays";
var patt=/ain/g;
console.log(patt.test(str))//true
console.log(patt.lastIndex)//8
console.log(patt.test(str))//true
console.log(patt.lastIndex)//17
console.log(patt.test(str))//false
console.log(patt.lastIndex)//0
console.log(patt.test(str))//true
console.log(patt.lastIndex)//8

  例子三:如何避免因由于lastIndex引起bug:每次都创建一个新的RegExp就 可以避免这个问题

var str="The rain in Spain stays";
console.log(/ain/g.test(str))//true
console.log(/ain/g.lastIndex)//0
console.log(/ain/g.test(str))//true
console.log(/ain/g.lastIndex)//0
console.log(/ain/g.test(str))//false
console.log(/ain/g.lastIndex)//0
console.log(/ain/g.test(str))//true
console.log(/ain/g.lastIndex)//0

 

 

  

正则的lastIndex 属性

原文:https://www.cnblogs.com/aidixie/p/11271186.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!