gpt4 book ai didi

javascript - 为什么反转全局正则表达式总是在 JavaScript 中返回 true

转载 作者:行者123 更新时间:2023-11-30 10:16:36 25 4
gpt4 key购买 nike

示例代码

这如广告所示:

var re = /abc/;
re.test("abc");
//true
!re.test("abc");
//false;

这不是:

var re2 = /abc/g;
//undefined
re2.test("abc");
//true
!re2.test("abc");
//true

什么给了?

我已经用多个正则表达式对其进行了测试,似乎 /g 标志使所有 ! 都返回 true。

如果有帮助,我正在使用 Chrome 34。

最佳答案

来自MDN page on .test() :

Use test() whenever you want to know whether a pattern is found in a string (similar to the String.search method); for more information (but slower execution) use the exec method (similar to the String.match method). As with exec (or in combination with it), test called multiple times on the same global regular expression instance will advance past the previous match.

因此,使用 g 标志将在每次连续调用 .test() 时移动字符串,前进到它找到的每个匹配项(与 相同的行为.exec()).

它通过修改正则表达式本身的一个名为 lastIndex 的属性来做到这一点,该属性告诉下一个 .test() 操作下次应该从哪里开始搜索字符串使用正则表达式(使用某些方法)。 g 标志告诉正则表达式使用 .lastIndex 属性。如果没有该标志,则不会使用该属性。该属性可以手动设置回 0,但如果您只是删除 g 标志,则不必担心。

除非您明确尝试使用此功能,否则您可能不想将 g 标志与 .test() 一起使用。

关于javascript - 为什么反转全局正则表达式总是在 JavaScript 中返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23344220/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com