aberg
aberg

Reputation: 269

JavaScript regex with variable pattern using RegExp constructor

Having the variable

var str = "asdasd asd 123213 100 Feet";

I can easily extract the string '100 Feet' using

str.match(/(\d+) feet/gi);

producing:

100 Feet

But let's say I want to specify the keyword 'feet' in a variable and use that in my regex evaluation - and so I attempt to use the RegExp constructor like below:

var keyWord = 'feet';
var pattern = '(\\d+) ' + keyWord;     
//pattern evaluates into '(\d+) feet', seemingly equivalent to the pattern shown above

var regex = new RegExp(pattern, 'g', 'i');
var result = str.match(regex); 

However, this does not match the string for some reason. Would anyone be able to shed some light into this?

Upvotes: 1

Views: 420

Answers (1)

antyrat
antyrat

Reputation: 27765

This happens because ignore case flag is not applied. Should be:

var regex = new RegExp(pattern, 'gi');

RegExp constructor doesn't have third param and flag param should consist of combination of different flags as simple chars.

Upvotes: 4

Related Questions