How do I concatenate regular expressions in javascript?
this is not what i am asking:
concatenate multiple regexes into one regex
is there a way to add regex to another (in javascript language) ?
the reason for this is to make the code easier to maintain (e.g. if the included string is long or easier to maintain by a non-programmer).
in python, for example, I would write something like:
regstr1 = 'dogs|cats|mice' regstr_container = '^animal: (cows|sheep|%s|zebra)$' % regstr1 re.compile(regstr_container)
however in javascript the regex is not a string.
re = /^animal: (rami|shmulik|dudu)$/;
or am I missing something?
+2
Berry tsakala
source
to share
2 answers
You don't need to use literal notation. Instead, you can create a new RegExp object.
var myRegex = new RegExp("^animal: (rami|shmulik|dudu)$");
+5
Cᴏʀʏ
source
to share
var regstr1 = 'dogs|cats|mice',
regstr_container = '^animal: (cows|sheep|'+ regstr1 +'|zebra)$',
regex = RegExp(regstr_container);
+2
Eli gray
source
to share