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"
.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745260974a4619211.html
评论列表(0条)