Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate regular expressions in JavaScript?

This is not what I'm asking for:

concatenate multiple regexes into one regex

Is there a way to append a regex into another one (in JavaScript language) ?

The reason for doing so is to simplify code maintenance (e.g. if the included string is long or easier to maintain by a non-programmer).

In Python, for example, i'd write something like:

regstr1 = 'dogs|cats|mice'
regstr_container = '^animal: (cows|sheep|%s|zebra)$' % regstr1
re.compile(regstr_container)

however, in JavaScript, the regular expression is not a string.

re = /^animal: (rami|shmulik|dudu)$/;

or am I missing something?

like image 547
Berry Tsakala Avatar asked Jan 24 '23 07:01

Berry Tsakala


2 Answers

You don't have to use the literal notation. You could instead create a new RegExp object.

var myRegex = new RegExp("^animal: (rami|shmulik|dudu)$");
like image 57
Cᴏʀʏ Avatar answered Jan 25 '23 20:01

Cᴏʀʏ


var regstr1 = 'dogs|cats|mice',
regstr_container = '^animal: (cows|sheep|'+ regstr1 +'|zebra)$',
regex = RegExp(regstr_container);
like image 26
Eli Grey Avatar answered Jan 25 '23 19:01

Eli Grey