admin管理员组文章数量:1417411
I recently came across a code snippet (a joke) where the test()
method of JavaScript's RegExp
object was used with an empty object as an argument. Here's the code:
console.log(new RegExp({}).test('mom')); // true
console.log(new RegExp({}).test('dad')); // false
Can someone explain why is it happens?
I recently came across a code snippet (a joke) where the test()
method of JavaScript's RegExp
object was used with an empty object as an argument. Here's the code:
console.log(new RegExp({}).test('mom')); // true
console.log(new RegExp({}).test('dad')); // false
Can someone explain why is it happens?
Share Improve this question asked Mar 20, 2024 at 23:02 AgorrecaAgorreca 68617 silver badges31 bronze badges 3-
1
try
console.log(new RegExp({}));
and see if you can figure it out – Jaromanda X Commented Mar 20, 2024 at 23:08 - It was explained in a ment on the Twitter post. – Dave Newton Commented Mar 20, 2024 at 23:13
- dad's get no love! :( – Ishan Commented Mar 21, 2024 at 2:00
2 Answers
Reset to default 8This is a curious fact. RegExp constructor accepts a string as its first argument. Since you are passing {}
it gets coerced to string, and the coercion of an object is the literal string [object Object]
.
By a fortuitous coincidence, the square brackets have a precise meaning in a regular expression, and it means "one of these characters of the set".
Thus, the regular expression is equal to [objectO ]
. In other words, your code is equal to:
console.log(new RegExp('[object Object]').test('mom'));
which is equal to:
console.log(new RegExp('[objectO ]').test('mom'));
which means: tests true
if any of these characters is present: o, b, j, e, c, t, O, space. mom
satisfies this condition, while dad
doesn't.
The RegExp
constructor casts the first argument to a string. An empty object bees
new RegExp('[object Object]')
Given this represents a regexp character class, essentially
/[objectO ]/
"mom"
passes because it contains an "o"
.
版权声明:本文标题:regex - Why does JavaScript return different results for RegExp test() method with empty object? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745260973a2650356.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论