How to concatenate regex literals in JavaScript?

Regular expressions (regex literals) are patterns used to match character combinations in strings. Sometimes, you need to combine multiple regex patterns into a single expression. Unlike strings, regex literals cannot be concatenated directly with the '+' operator.

To concatenate regex literals, you must extract their source patterns and flags, combine them properly, and create a new RegExp object.

Syntax

Follow this approach to concatenate regex literals:

let allFlags = regex1.flags + regex2.flags;
let uniqueFlags = [...new Set(allFlags.split(''))].join('');
let combined = new RegExp(regex1.source + regex2.source, uniqueFlags);

This extracts the source patterns and flags from both regex literals, removes duplicate flags, and creates a combined regex.

Basic Concatenation Example

Here's how to concatenate two regex literals with different flags:

<html>
<body>
   <h2>Concatenating Regex Literals in JavaScript</h2>
   <div id="output"></div>
   <script>
      let output = document.getElementById('output');
      
      // Define two regex literals
      let regex1 = /hello/i;  // case-insensitive
      let regex2 = /world/g;  // global flag
      
      // Combine flags and remove duplicates
      let allFlags = regex1.flags + regex2.flags;
      let uniqueFlags = [...new Set(allFlags.split(''))].join('');
      
      // Create combined regex
      let combined = new RegExp(regex1.source + regex2.source, uniqueFlags);
      
      output.innerHTML += "First regex: " + regex1 + "<br>";
      output.innerHTML += "Second regex: " + regex2 + "<br>";
      output.innerHTML += "Combined regex: " + combined + "<br>";
      
      // Test the combined regex
      let testString = "HelloWorld";
      output.innerHTML += "Test string '" + testString + "' matches: " + 
                         combined.test(testString);
   </script>
</body>
</html>

Interactive Regex Combiner

This example lets you input custom regex patterns and test them:

<html>
<body>
   <h2>Interactive Regex Concatenation</h2>
   <label>Regex 1: <input type="text" placeholder="hello" id="regex1"></label>
   <label>Flags: <input type="text" placeholder="i" id="flag1"></label>
   <br><br>
   <label>Regex 2: <input type="text" placeholder="world" id="regex2"></label>
   <label>Flags: <input type="text" placeholder="g" id="flag2"></label>
   <br><br>
   <label>Test String: <input type="text" placeholder="HelloWorld" id="str"></label>
   <br><br>
   <button onclick="combineAndTest()">Combine & Test Regex</button>
   <div id="result"></div>
   
   <script>
      function combineAndTest() {
         let result = document.getElementById('result');
         
         try {
            // Create regex objects from inputs
            let regex1 = new RegExp(
               document.getElementById('regex1').value || 'hello',
               document.getElementById('flag1').value || ''
            );
            let regex2 = new RegExp(
               document.getElementById('regex2').value || 'world',
               document.getElementById('flag2').value || ''
            );
            
            // Combine flags and remove duplicates
            let allFlags = regex1.flags + regex2.flags;
            let uniqueFlags = [...new Set(allFlags.split(''))].join('');
            
            // Create combined regex
            let combined = new RegExp(regex1.source + regex2.source, uniqueFlags);
            
            // Test against input string
            let testStr = document.getElementById('str').value || 'HelloWorld';
            let matches = combined.test(testStr);
            
            result.innerHTML = `
               <strong>Combined Regex:</strong> ${combined}<br>
               <strong>Test Result:</strong> "${testStr}" matches: ${matches}
            `;
         } catch (error) {
            result.innerHTML = `<span style="color: red;">Error: ${error.message}</span>`;
         }
      }
   </script>
</body>
</html>

String-Based Concatenation

You can also combine regex patterns as strings before creating the RegExp object:

<html>
<body>
   <h2>String-Based Regex Concatenation</h2>
   <div id="output"></div>
   <script>
      let output = document.getElementById('output');
      
      // Define regex patterns as strings
      let part1 = "java";
      let part2 = "script";
      
      // Combine strings and create regex
      let combinedPattern = new RegExp(part1 + part2, "gi");
      
      output.innerHTML += "Combined pattern: " + combinedPattern + "<br>";
      
      // Test the pattern
      let testString = "I love JavaScript programming!";
      let matches = testString.match(combinedPattern);
      output.innerHTML += "Matches in '" + testString + "': " + 
                         (matches ? matches.join(', ') : 'none');
   </script>
</body>
</html>

Key Considerations

When concatenating regex literals, remember:

  • Flag Handling: Duplicate flags are automatically removed using Set
  • Pattern Order: The order of concatenation affects matching behavior
  • Escaping: Special regex characters in source patterns remain escaped
  • Performance: Pre-compiled literals are faster than constructor-created patterns

Conclusion

Regex literal concatenation requires extracting source patterns and flags, then creating a new RegExp object. This technique is useful for building complex patterns from simpler components while preserving all necessary flags.

Updated on: 2026-03-15T23:19:01+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements