Javascript

How can I concatenate regex literals in JavaScript

27 September 2026 · 6 min read

How can I concatenate regex literals in JavaScript

Building dynamic and flexible search patterns is a cornerstone of robust JavaScript applications, and often, this involves combining existing regular expressions. If you’ve ever found yourself needing to join two or more regex patterns into a single, more complex one, you’re likely asking: How can I concatenate regex literals in JavaScript? The good news is that JavaScript provides powerful mechanisms to achieve this, moving beyond simple string concatenation to create valid and functional regular expression objects. This capability is essential for scenarios where patterns are built conditionally or retrieved from various sources, allowing developers to construct sophisticated matching logic on the fly. Understanding the intricacies of the RegExp constructor and the source property is key to mastering this technique, ensuring your dynamic regular expressions behave exactly as intended.

Understanding JavaScript Regular Expressions

Regular expressions, or regex, are sequences of characters that define a search pattern. In JavaScript, you can create them in two primary ways: using a regular expression literal (e.g., /pattern/flags) or by using the RegExp constructor (e.g., new RegExp("pattern", "flags")). While literals are great for static, unchanging patterns, the constructor becomes indispensable when your pattern itself needs to be dynamic, built from variables or user input. This distinction is crucial when you need to concatenate regex literals, as direct string addition of literals won’t produce a valid combined regex object.

The flexibility of JavaScript regex extends to various flags that modify the search behavior, such as i for case-insensitive matching, g for global searching, and m for multi-line matching. When concatenating patterns, managing these flags becomes an important consideration. For instance, if you combine two patterns, each with its own set of flags, you’ll need a strategy to merge or prioritize them effectively for the resulting regular expression. The RegExp object also exposes a source property, which returns the string representation of the pattern without its leading and trailing slashes or flags. This property is the linchpin for combining patterns, as it provides the raw pattern string that can then be manipulated.

According to MDN Web Docs, the RegExp constructor is the preferred method for creating regular expressions when the pattern is unknown until runtime or when you need to build it from dynamic parts. This aligns perfectly with the need to concatenate regex literals, as you’re essentially building a new pattern string from existing components. Mastering this constructor is fundamental for any JavaScript developer looking to implement advanced text processing and validation logic, especially when dealing with complex data structures or user-generated content. Learn more about the RegExp constructor on MDN.

Methods to Concatenate Regex Literals in JavaScript

The most effective and common way to concatenate regex literals in JavaScript is by leveraging the RegExp constructor and the source property of existing regex objects. This approach allows you to extract the raw pattern string from each regex, combine them into a new single string, and then create a new RegExp object with this combined pattern and any desired flags. This method ensures that special characters within the individual patterns are handled correctly and that the resulting pattern is a valid regular expression.

To concatenate regex literals in JavaScript, you should utilize the source property of each RegExp object to extract their pattern strings, combine these strings, and then pass the resulting string to the RegExp constructor along with any desired flags. This process correctly merges the patterns while allowing for dynamic flag management, providing a robust solution for building complex search criteria.

Using the RegExp Constructor with the source Property

This method is straightforward and highly recommended. Each regular expression object in JavaScript has a source property, which returns the pattern part of the regex as a string, stripped of its delimiters (/) and flags. You can then concatenate these source strings and pass the result to a new RegExp constructor.

  1. Define your initial regex literals: Start with the patterns you wish to combine.
  2. Extract the source property: Access the .source of each regex object to get its raw pattern string.
  3. Concatenate the source strings: Join these strings using standard JavaScript string concatenation methods (e.g., + or template literals).
  4. Create a new RegExp object: Pass the combined string to the RegExp constructor, along with any desired flags.

Here’s an example demonstrating this process:

const pattern1 = /apple/; const pattern2 = /banana/i; const pattern3 = /cherry/; // Extract source strings const source1 = pattern1.source; // "apple" const source2 = pattern2.source; // "banana" const source3 = pattern3.source; // "cherry" // Concatenate the source strings, perhaps with a logical OR const combinedSource = ${source1}|${source2}|${source3}; // "apple|banana|cherry" // Define desired flags for the new regex. // Here, we combine flags. If one had 'i' and another 'g', you might choose 'ig'. const combinedFlags = 'gi'; // Example: global and case-insensitive // Create the new RegExp object const combinedRegex = new RegExp(combinedSource, combinedFlags); console.log(combinedRegex); // Outputs: /apple|banana|cherry/gi const text = "I like Apple, banana, and Cherry."; console.log(text.match(combinedRegex)); // Matches all three 

This method ensures proper escaping of special characters within the original patterns, as the .source property already provides the correctly escaped string. For instance, if you had /d\.e/, its source would be "d\\.e", which is then safely incorporated into the new regex.

Infographic here
Handling Flags and Special Characters During Concatenation ----------------------------------------------------------

When you concatenate regex literals in JavaScript, managing flags and ensuring proper handling of special characters are critical steps. Simply joining pattern strings can lead to unexpected behavior if not done carefully. The RegExp constructor offers a robust solution, but developers must be aware of how flags are inherited or overridden, and how special characters within the patterns might interact.

Question & Answer :
Is it possible to do something like this?

var pattern = /some regex segment/ + /* comment here */ /another segment/; 

Or do I have to use new RegExp() syntax and concatenate a string? I’d prefer to use the literal as the code is both more self-evident and concise.

Here is how to create a regular expression without using the regular expression literal syntax. This lets you do arbitrary string manipulation before it becomes a regular expression object:

var segment_part = "some bit of the regexp"; var pattern = new RegExp("some regex segment" + /*comment here */ segment_part + /* that was defined just now */ "another segment"); 

If you have two regular expression literals, you can in fact concatenate them using this technique:

var regex1 = /foo/g; var regex2 = /bar/y; var flags = (regex1.flags + regex2.flags).split("").sort().join("").replace(/(.)(?=.*\1)/g, ""); var regex3 = new RegExp(regex1.source + regex2.source, flags); // regex3 is now /foobar/gy 

It’s just more wordy than just having expression one and two being literal strings instead of literal regular expressions.