正则的lastIndex 属性

 

简介:正则的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

 

 

  

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值