Parth Thakkar
Parth Thakkar

Reputation: 5475

Regexp showing unexpected Type error in javascript

This is quite bizarre, no idea why it happens, but here it is. When I do this:

/^\d+$/.test('16')

it works fine. But when I do something like the following, I get an error

var t = /^\d+$/.test;
t('16');

The error I get is this:

TypeError: Method RegExp.prototype.test called on incompatible receiver [object Window]

I don't know what it has got to do with Window over here....any idea?

Upvotes: 6

Views: 2886

Answers (3)

JJ Geewax
JJ Geewax

Reputation: 10579

I saw this come up when I wanted to filter an array by things matching a regular expression, and fixed it using bind:

var items = ['a', 'b', 'c', 'A'];
var pattern = new RegExp('^a$', 'i');
var matches = items.filter(pattern.test.bind(pattern));
console.log(matches);

Which results as:

['a', 'A']

Upvotes: 0

Sjoerd
Sjoerd

Reputation: 75578

Alternatively, you can use bind to create a new function that uses the regex as this:

var r = /^\d+$/;
var t = r.test.bind(r)
t(16)

Upvotes: 10

johusman
johusman

Reputation: 3472

When you do /^\d+$/.test('16') you are invoking the test function with your regexp as the this object (i.e. as a method invocation on an object).

When you run t(16) you have no object specified, and so this defaults to the top object, which is window.

To replicate the first behavior you'd have to do this:

var r = /^\d+$/;
var t = r.test;
t.call(r, 16);

Upvotes: 9

Related Questions