Search code examples
javascriptregex

Combining regular expressions in Javascript


Is it possible to combine regular expressions in javascript.

For ex:

 var lower = /[a-z]/;
 var upper = /[A-Z]/;
 var alpha = upper|lower;//Is this possible?

ie. can i assign regular expressions to variables and combine those variables using pattern matching characters as we do in regular expressions


Solution

  • The answer is yes!

     let lower = /[a-z]/;
     let upper = /[A-Z]/;
    

    Then you can combine them dynamically by using the .source attribute:

    let finalRe = new RegExp(lower.source + "|" + upper.source);