How to Concatenate a Regular Expression
Jul 8, 2021
To concatenate a regular expression in JavaScript, you can use a combination of the +
operator and the RegExp()
class as shown below.
You need to combine both the RegExp source (the string representation of the RegExp) and flags (options for the RegExp).
let reg = /mastering/g;
let exp = /js/i;
let pattern = concatRegexp(reg, exp);
let string = 'masteringjs';
pattern.test('masteringjs'); // true
function concatRegexp(reg, exp) {
let flags = reg.flags + exp.flags;
flags = Array.from(new Set(flags.split(''))).join();
return new RegExp(reg.source + exp.source, flags);
}
You are responsible for removing duplicate flags.
If you pass a duplicate flag to new RegExp()
, JavaScript will throw a SyntaxError: Invalid flags
.
More Fundamentals Tutorials
- How to Add 2 Arrays Together in JavaScript
- The String `match()` Function in JavaScript
- Convert a Set to an Array in JavaScript
- What Does Setting the Length of a JavaScript Array Do?
- Get the Last Element in an Array in JavaScript
- Skip an Index in JavaScript Array map()
- Conditionally Add an Object to an Array in JavaScript