gpt4 book ai didi

javascript - RegExp 对象保留先前的匹配项

转载 作者:行者123 更新时间:2023-12-02 14:07:30 24 4
gpt4 key购买 nike

考虑这个 Javascript 正则表达式代码:

v = 'The dog jumped over the moon';

// Matches
if (v.match(/(jump)ed/)) {
alert('Initial: ' + RegExp.$1); // Alerts "jump"
}

// Obviously not matched, but RegExp object retains previous match
if (v.match(/(gygyujgujy)/)) {
alert(RegExp.$1);
}

// Alerts "jump" but shouldn't this be null/false etc?
alert('Final: ' + RegExp.$1);

尽管不匹配,第二个正则表达式仍保持第一个正则表达式匹配。

由于第二个正则表达式不匹配,RegExp 对象不应该为空吗?

最佳答案

来自https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/n

"The $1, ..., $9 properties are static, they are not a property of an individual regular expression object. Instead, you always use them as RegExp.$1, ..., RegExp.$9.

The values of these properties are read-only and modified whenever successful matches are made."

由于您的第二个 if 语句从未匹配任何内容,因此不会为 $1 分配新值

关于javascript - RegExp 对象保留先前的匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39919875/

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