Saturday, October 25, 2025
HomeLanguagesJavascriptHow to concatenate regex literals in JavaScript ?

How to concatenate regex literals in JavaScript ?

Regex is a sequence of pattern that is used for matching with a pattern. While searching for data in a text, the search pattern is described for what we are searching for. It can be a single character or a more complex pattern. It can be used to perform all types of text searches. Regex has its own static and instance properties.

Syntax:

/pattern/modifiers

Example: A regular expression.

/gfg/g

Where,

  • gfg is a pattern (to be used in a search).
  • g is a modifier (modifies the search to be case-insensitive).

The concatenation of Regex in the programming world can be understood as combining text patterns to obtain a new text pattern, such as “Hello” + “World” is /HelloWorld/. Whenever RegExp() is called, it creates a new RegExp object.

Example 1: This example creating an expression without actually using the Regex literal syntax. This allows you to make arbitrary string manipulation before it becomes a Regex object.

Javascript




function gfg() {
    var segment_part = " neveropen |"
        + " A computer science portal for neveropen";
  
    var pattern = new RegExp("GFG:" +
            /*comment here */
            segment_part +
            /* that was defined just now */
            "is a computer science portal");
  
    console.log(pattern);
}
gfg();


Output: 

/GFG: neveropen | A computer science portal for neveropenis a computer science portal/

 Example 2: If you have two Regex literals, you can concatenate them using a technique where it removes duplicates, but keep the unique values in order, joining both the regex literals. Example: /hello/y + / world/g would be /hello world/gy 

Javascript




function gfg() {
    var regex1 = /neveropen/g;
    var regex2 = / for neveropen/y;
    var flags = (regex1.flags +
        regex2.flags).split("")
            .sort().join("")
              
            .replace(/(.)(?=.*\1)/g, "");
    var regex3 = new RegExp(regex1.source
                + regex2.source, flags);
                  
    console.log(regex3);
}
gfg();


Output: 

/neveropen for neveropen/gy
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS