0

I really like Regular Expressions. I was wondering if this kind of things can be done in JavaScript.

Imagine that you want to match the words foo and bar, but only when they are followed by "?" Or "!". I know that this simple case could be done with x(?=y), but my intention here is to know if you can place one RegEx inside another, as it would be great for more difficult scenarios.

I mean something like this:

var regex1 = /foo|bar/;
var regex2 = /{regex1}[\?\!]/;

This would simplify very complex regexes and would make some patters reusable without having to write the same patterns every time you need it. It would be something like a RegEx variable, if that makes sense.

Is it possible?

Tushar
  • 85,780
  • 21
  • 159
  • 179
Daniel Reina
  • 5,764
  • 1
  • 37
  • 50
  • Use `RegExp` constructor notation, see [How do you pass a variable to a Regular Expression JavaScript?](http://stackoverflow.com/questions/494035/how-do-you-pass-a-variable-to-a-regular-expression-javascript). – Wiktor Stribiżew Aug 11 '16 at 10:47

1 Answers1

1

Use RegExp constructor.

new RegExp('(?:' + regex1.source + ')[?!]')

regex1.source will give the actual regex as string without the delimiters and flags which then can be passed to the RegExp constructor to create new regex.

Also, note that there is no need to escape ? and ! when used inside character class.

var regex1 = /foo|bar/;
var regex = new RegExp('(?:' + regex1.source + ')[?!]')
console.log(regex);
Tushar
  • 85,780
  • 21
  • 159
  • 179