Mashing two regular expressions together in JavaScript on the fly

var pattern1 = /Aug/;
var pattern2 = /ust/;
var fullpattern = (new RegExp( (pattern1+'').replace(/^\/(.*)\/$/,'$1') + (pattern2+'').replace(/^\/(.*)\/$/,'$1') ));

Explanation:

  • pattern1+'' turns (“casts”) the regular expression object into a string.
  • .replace(/^\/(.*)\/$/,'$1') removes the beginning and ending slashes from the pattern
  • new RegExp() turns the resultant string into a regular expression object. There is no need to add back a regular expression delimiter (i.e. slashes usually) since the RegExp() function (“constructor”) adds the delimiter if it is lacking.
  • If you want the resultant expression to have a flag, for example i, you add it so: new RegExp(string,'i');
  • This code is quite unreadable and you might be doing yourself and others a kindness if you use a less clever method. To make it more readable, the technique can be wrapped in a function:
var rmash = function(reg1,reg2) {
var fullpattern = (new RegExp( (reg1+'').replace(/^\/(.*)\/$/,'$1') + (reg2+'').replace(/^\/(.*)\/$/,'$1') ));
return fullpattern;
};

var my_new_pattern = rmash(pattern1,pattern2);

Generalizing the mash function to handle an arbitrary number of regular expressions and flags is left as an exercise.

Commenting rules: Politeness is the only rule. We respect your right to disagree with anything we say. But comments with profanity and insults will be deleted.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments