gpt4 book ai didi

Javascript 常规异常在 Chrome 和 Firefox 中每两次尝试匹配一次字符串

转载 作者:行者123 更新时间:2023-11-30 10:48:06 24 4
gpt4 key购买 nike

我在 javascript 中有以下正则表达式:

var the_regexp = /^\/([!\/]*)\/?(\w*)\??([\=|\w]*)\/?$/gi

它在 Firefox 和 Chrome 控制台中,每两次尝试都会找到字符串“/d”的匹配项。

>the_regexp
/^\/([!\/]*)\/?(\w*)\??([\=|\w]*)\/?$/gi
>the_regexp.exec("/d")
null
>the_regexp.exec("/d")
["/d", "", "d", ""]
>the_regexp.exec("/d")
null
>the_regexp.exec("/d")
["/d", "", "d", ""]

有人可以解释这种行为吗?

最佳答案

MDN Docs :

If your regular expression uses the "g" flag, you can use the exec method multiple times to find successive matches in the same string. When you do so, the search starts at the substring of str specified by the regular expression's lastIndex property

所以当你的正则表达式有一个 g 标志,并且你使用了一次 exec 方法时,下次你执行它时它会在第一次匹配之后搜索匹配。在这种情况下,没有:exec 将返回 null 并且 lastIndex 属性将被重置。

例如:

var str = "abcdef";
// ^ starting index for search is here
var regex = /ab/g;

regex.exec(str);
// str: "abcdef"
// ^ starting index for search is now here

regex.exec(str);
// no match found from starting index, return null and reset
// str: "abcdef"
// ^ starting index reset

对不起我的措辞不当,我还没完全清醒......

关于Javascript 常规异常在 Chrome 和 Firefox 中每两次尝试匹配一次字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7124794/

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