regex - Why does JavaScript return different results for RegExp test() method with empty object? - Stack Overflow

I recently came across a code snippet (a joke) where the test() method of JavaScript's RegExp obje

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
Add a ment  | 

2 Answers 2

Reset to default 8

This 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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信