1

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?

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Aha! I thought the constructor allowed the flags to be entered like so: RegExp(pattern, flag1, flag2) -> RegExp(pattern, 'g', 'i') But, as you pointed out, RegExp(pattern, 'gi') does the trick!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.