1

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?

1

1 Answer 1

4

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);

Sign up to request clarification or add additional context in comments.

1 Comment

I think OP uses {} as in C# 6.0 interpolated strings. new RegExp('(?:' + regex1.source + ')[?!]') is necessary then.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.