Regex.test(value) returns 记录时为真,但在 if 语句中为假

Regex.test(value) returns true when logged but false within an if statement

我发现我的代码有些奇怪。我有一个正则表达式来检查英国邮政编码,它使用捕获组并且工作正常,除非在 if 语句中。要测试的代码位于验证器 class 中,该验证器传递一个 HTML 节点列表,其中包含表单中的所有字段。

例如,当我在 HTML 输入字段的 pattern 标记内使用它时,它的行为与您预期的一样。就像我 console.log(regex.test(field.value)) 时一样。但是,当我将它放入 if 语句时,它似乎每次都失败。

正则表达式如下:

/\b([a-zA-Z]{1,2}[0-9]{1,2}[a-zA-Z]?){1}( |-)?([0-9]{1,2}[a-zA-Z]{1,2}){1}\b/

输入字段如下:

<input required pattern="\b([a-zA-Z]{1,2}[0-9]{1,2}[a-zA-Z]?){1}( |-)?([0-9]{1,2}[a-zA-Z]{1,2}){1}\b" inputmode="text" class="form-field" type="text" name="postcode" id="contactPostcode" placeholder="Postcode eg NW2 8BZ" />

测试代码如下:

validate(fields)

// ... omitted ... //

let errors = [];

const postcodeRegex = /\b([a-zA-Z]{1,2}[0-9]{1,2}[a-zA-Z]?){1}( |-)?([0-9]{1,2}[a-zA-Z]{1,2}){1}\b/;

postcodeRegex.lastIndex = 0;

for (let field of fields) {

    if(field.name === 'postcode') {
        console.log(postcodeRegex.test(field.value))
        if(!postcodeRegex.test(field.value)) {
            errors.push({
                field: field.getAttribute('name'),
                error: 'Illegal character detected'
            });
            continue;
        }
    }

}

console.log check returns true 但是 if 语句每次都检查 returns false 我不明白为什么两次相同的检查会输出不同的结果,有没有人有有什么建议吗?我猜这里有什么事情让我头疼。

谢谢

编辑澄清:控制台日志的 true 但 if 语句仍在 执行

根据文档 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test

As with exec() (or in combination with it), test() called multiple times on the same global regular expression instance will advance past the previous

所以这就是你第二次报错的原因。

试试这个:

var res = postcodeRegex.test(field.value);
console.log(res)
        if(!res) {