Chris Montgomery
Chris Montgomery

Reputation: 2354

javascript regex test() fails when regex in variable during jasmine test

I'm trying to do a simple js regex pattern match against a string during a jasmine test. This line works as expected:

(/[^0-9\.]/g).test('$'); // true

However, when the regex is stored in a variable, it breaks:

var NON_CURRENCY_VALUES = /[^0-9\.]/g; 
NON_CURRENCY_VALUES.test('$'); // false

Both return true, as expected, when run from the console. However, when run from inside the jasmine test, it breaks.

see plunker

Upvotes: 3

Views: 1916

Answers (2)

Explosion Pills
Explosion Pills

Reputation: 191749

test has weird and unhelpful behavior

test called multiple times on the same global regular expression instance will advance past the previous match.

You can get around this by setting RegExp.lastIndex = 0 before each match is attempted, but be wary of this behavior.

http://plnkr.co/edit/cne6He?p=preview

Upvotes: 2

anubhava
anubhava

Reputation: 785156

NON_CURRENCY_VALUES.test('$'); is returning true for me.

However to store a regex in a variable you can also use RegExp:

var NON_CURRENCY_VALUES = new RegExp("[^0-9\.]", "g");

Upvotes: 2

Related Questions