简体   繁体   中英

Javascript Dynamic Regex Parsing

I'm trying to a regular expression like so

var regex_pattern = '/cat|bat|dog/i';

regex = new RegExp(regex_pattern, "i");

var string = "A dog saw a cat and a bat";

string.match(regex);

But it does not seem to be parsing. What am I doing wrong with this expression?

You've put a regex literal syntax inside a string. You should either use the regex literal syntax:

var regex = /cat|bat|dog/i;

Or pass a string (without delimiters/modifiers) as the first argument to the RegExp constructor :

var regex = new RegExp('cat|bat|dog', 'i');

Also you'll need the g flag (global modifier) to test the regular expression against all possible matches, otherwise only the first match will be returned.

Complete example:

var regex = /cat|bat|dog/ig; //or new RegExp('cat|bat|dog', 'ig');
var string = "A dog saw a cat and a bat";
var matches = string.match(regex);
matches; //["dog", "cat", "bat"]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM