Open In App

How to clone a given regular expression in JavaScript ?

Last Updated : 17 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:-

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:

Output 2:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads