gpt4 book ai didi

javascript - .each 错误中的 jQuery 正则表达式测试

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

好的,所以我有多个接收 UUID 代码的输入。因此,我使用 jQuery 中的 .each 函数逐一验证输入是否为 UUID 代码。所以这是我到目前为止的代码:

function validateAll(){
var regex = /^[a-zA-Z0-9]{8}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{12}$/ig;
$('input.offer').each(function(x){
if($(this).val() !== ""){
console.log(x+" - "+$(this).val()+" - "+regex.test($(this).val()));
}
});
return true;
}

现在当我用两个输入运行它时:00000000-0000-0000-0000-000000000000 这是我在控制台中得到的:

0 - 00000000-0000-0000-0000-000000000000 - 真

1 - 00000000-0000-0000-0000-000000000000 - 假

为什么 regex.test() 验证第一个而不是第二个?谢谢。

最佳答案

您需要将正则表达式实例化带入循环中 - 它不能针对另一个字符串进行重新测试。

function validateAll(){
$('input.offer').each(function(x) {
var regex = /^[a-zA-Z0-9]{8}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{12}$/ig;
if($(this).val() !== ""){
console.log(x + " - " + $(this).val() + " - " + regex.test($(this).val()));
}
});
return true;
}

Example fiddle

第二次迭代失败的原因:

when [the regex] is a global regular expression. It will attempt to match from the index of the last match in any previous string.

文章:Be careful when reusing regex objects

关于javascript - .each 错误中的 jQuery 正则表达式测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19299228/

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