javascript/ regex

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?

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.

暂无
暂无

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

Related Question JavaScript: RegExp constructor vs RegEx literal javascript syntax for regex using variable as pattern Javascript regex match using RegExp A weird problem with variable in JavaScript regexp pattern using variable in jquery, javascript regexp JavaScript regex pattern concatenate with variable Javascript regexp: Using variables in backreference pattern? Javascript replacing string pattern using RegExp? Javascript - how to identify the pattern using RegExp Is literal pattern inside a RegExp constructor already constructed to node.js regex before the constructor acts on it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM