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
to combine two expressions or more, put every expression in brackets, and use: *? This are the signs to combine, in order of relevance: ?
In JavaScript, you can write RegExp patterns using simple patterns, special characters, and flags.
JavaScript RegExp test() The test() method tests for a match in a string. If it finds a match, it returns true, otherwise it returns false.
The answer is yes! You have to initialize the variable under the RegExp class:
var lower = new RegExp(/--RegexCode--/); var upper = new RegExp(/--RegexCode--/);
hence, regex can be dynamically created. After creation:
"sampleString".replace(/--whatever it should do--/);
Then you can combine them normally, yes.
var finalRe = new RegExp(lower.source + "|" + upper.source);
If regexps are not known beforehand,
var one = /[a-z]/; var two = /[A-Z]/; var one_or_two = new RegExp("(" + one.source + ")|(" + two.source + ")")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With