gpt4 book ai didi

javascript正则表达式在Chrome控制台中使用相同的表达式得到不同的答案

转载 作者:行者123 更新时间:2023-12-01 01:50:37 25 4
gpt4 key购买 nike

我想在 Chrome 控制台中测试 Javascript Regex。然而,我用相同的表达得到不同的答案(参见图片)。如果我使用原始文字来测试,我可以得到正确的答案。这是什么原因呢?

re = /^[a-z][0-9a-z]*$/g;
console.log(re.test("a34"));
console.log(re.test("a34"));
console.log(re.test("a34"));
console.log(re.test("a34"));
console.log(/^[a-z][0-9a-z]*$/g.test("a23"));
console.log(/^[a-z][0-9a-z]*$/g.test("a23"));

最佳答案

直接来自docs :

Use test() whenever you want to know whether a pattern is found in a string. test() returns a boolean, unlike the String.prototype.search() method, which returns the index (or -1 if not found). To get more information (but with slower execution), use the exec() method (similar to the String.prototype.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.

关于javascript正则表达式在Chrome控制台中使用相同的表达式得到不同的答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51575556/

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