正则表达式中lastIndex如何影响匹配结果的详细讨论是什么?

更新于
2026-07-29 09:34:11
19阅读来源:SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计561个文字,预计阅读时间需要3分钟。

正则表达式中lastIndex如何影响匹配结果的详细讨论是什么?

前言:今天遇到一个问题,使用正则表达式去检查同一字符串时,交换单引号和反引号是否返回true和false。

具体步骤如下:

1.定义字符串,如 hello'world``hello

2.创建正则表达式 `/[\s]/g`,用于查找字符串中的空格

3.使用正则表达式的`test`方法检查字符串是否包含空格

4.如果包含空格,则交换单引号和反引号

5.重新检查字符串是否包含空格,返回true或false

代码示例:

javascriptlet str=hello'world``hello;let reg=/[\s]/g;

if (reg.test(str)) { str=str.replace(/'/g, '`').replace(/`/g, ');}

正则表达式中lastIndex如何影响匹配结果的详细讨论是什么?

console.log(reg.test(str)); // 输出:false

前言

今天遇到一个问题,用正则表达式去检查同一个字符串时,交替返回true和false。无奈之下,重新翻了翻权威指南,发现罪魁祸首原来是lastIndex。可在控制台尝试下

let reg = /[\d]/g //undefined reg.test(1) //true reg.test(1) //false

lastIndex

lastIndex在权威指南中是如下解释:它是一个可读/写的整数。如果匹配模式带有g修饰符,这个属性存储在整个字符串中下次索引的开始位置,这个属性会被exec()和test()用到。还是上面的例子,观察下lastIndex属性

let reg = /[\d]/g //有修饰符g //undefined reg.lastIndex //0 reg.test(1) //true reg.lastIndex //匹配一次后,lastIndex改变 //1 reg.test(1) //从index 1 开始匹配 //false reg.lastIndex //0 reg.test(1) //true reg.lastIndex //1

第一次使用test()匹配成功后,lastIndex被设为匹配到的结束位置,就是1;第二次再test()时,从index 1 开始匹配,匹配失败,lastIndex重置为0 。这样就造成了匹配结果与预期不符

解决

1、不使用 g 修饰符

reg = /[\d]/ ///[\d]/ reg.test(1) //true reg.test(1) //true reg.lastIndex //0 reg.test(1) //true reg.lastIndex

2、test()之后手动设置lastIndex = 0

以上这篇详谈lastIndex对正则结果的影响就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持易盾网络。

本文共计561个文字,预计阅读时间需要3分钟。

正则表达式中lastIndex如何影响匹配结果的详细讨论是什么?

前言:今天遇到一个问题,使用正则表达式去检查同一字符串时,交换单引号和反引号是否返回true和false。

具体步骤如下:

1.定义字符串,如 hello'world``hello

2.创建正则表达式 `/[\s]/g`,用于查找字符串中的空格

3.使用正则表达式的`test`方法检查字符串是否包含空格

4.如果包含空格,则交换单引号和反引号

5.重新检查字符串是否包含空格,返回true或false

代码示例:

javascriptlet str=hello'world``hello;let reg=/[\s]/g;

if (reg.test(str)) { str=str.replace(/'/g, '`').replace(/`/g, ');}

正则表达式中lastIndex如何影响匹配结果的详细讨论是什么?

console.log(reg.test(str)); // 输出:false

前言

今天遇到一个问题,用正则表达式去检查同一个字符串时,交替返回true和false。无奈之下,重新翻了翻权威指南,发现罪魁祸首原来是lastIndex。可在控制台尝试下

let reg = /[\d]/g //undefined reg.test(1) //true reg.test(1) //false

lastIndex

lastIndex在权威指南中是如下解释:它是一个可读/写的整数。如果匹配模式带有g修饰符,这个属性存储在整个字符串中下次索引的开始位置,这个属性会被exec()和test()用到。还是上面的例子,观察下lastIndex属性

let reg = /[\d]/g //有修饰符g //undefined reg.lastIndex //0 reg.test(1) //true reg.lastIndex //匹配一次后,lastIndex改变 //1 reg.test(1) //从index 1 开始匹配 //false reg.lastIndex //0 reg.test(1) //true reg.lastIndex //1

第一次使用test()匹配成功后,lastIndex被设为匹配到的结束位置,就是1;第二次再test()时,从index 1 开始匹配,匹配失败,lastIndex重置为0 。这样就造成了匹配结果与预期不符

解决

1、不使用 g 修饰符

reg = /[\d]/ ///[\d]/ reg.test(1) //true reg.test(1) //true reg.lastIndex //0 reg.test(1) //true reg.lastIndex

2、test()之后手动设置lastIndex = 0

以上这篇详谈lastIndex对正则结果的影响就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持易盾网络。