Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to clone a given regular expression in JavaScript ?

  • Difficulty Level : Medium
  • Last Updated : 21 May, 2021

In this article, we will know How to clone a regular expression using JavaScript. We can clone a given regular expression using the constructor RegExp().

The syntax of using this constructor has been defined as follows:-

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

Syntax:

new RegExp(regExp , flags)

Here regExp is the expression to be cloned and flags determine the flags of the clone. There are mainly three types of flags that are used.



  • g:global flag with this flag the search looks for global match.
  • i: With this flag the search is case-insensitive.
  • m: With this flag we perform multi line matching.

Let us now look how we can clone a given regular expression using RegExp( ) constructor in Javascript.

Example:-

HTML




<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
  
    <script src=
    </script>
    <title>Clone a given regular expression</title>
  </head>
  <body style="text-align: center">
    <p>Enter Regular Expression to clone</p>
  
    <input type="text" id="data" name="input" /><br />
    <button id="b1">Clone Regex</button>
    <div id="display"></div>
  
    <script>
      function cloneRegex(input, outputflag) {
        var pattern = input.source;
        const flags = [...new Set(input.flags + outputflag)].join("");
        // Using RegExp constructor to  for cloning regular expressions,
        // optionally while modifying flag also.
        return new RegExp(pattern, flags);
      }
  
      //Taking User data as input
      var d = $("#data").val();
  
      var regex = new RegExp(d, "i");
      //Passing user data to cloneRegex function with g set as flag.
      var clonedregex = cloneRegex(regex, "g");
  
      $("#b1").click(function () {
        $("#display").html("Cloned regex is as follows:-" + clonedregex);
      });
    </script>
  </body>
</html>

Output 1:

Output2:




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!