Sometimes, we want to concatenate regex literals in JavaScript.
In this article, we’ll look at how to concatenate regex literals in JavaScript.
How to concatenate regex literals in JavaScript?
To concatenate regex literals in JavaScript, we can get the regex pattern with the source property and then we get the flags with various properties.
For instance, we write
const r1 = /abc/g;
const r2 = /def/;
const r3 = new RegExp(
r1.source + r2.source,
(r1.global ? "g" : "") +
(r1.ignoreCase ? "i" : "") +
(r1.multiline ? "m" : "")
);
to use the source property to get the /abc/ and /def patterns and concatenate them.
And then we use the global, ignoreCase, and multline to get those flags from r1.
Then we concatenate the patterns and flags together and put them in the RegExp constructor.
Conclusion
To concatenate regex literals in JavaScript, we can get the regex pattern with the source property and then we get the flags with various properties.