w3resource

JavaScript: Clone a given regular expression

JavaScript fundamental (ES6 Syntax): Exercise-63 with Solution

Clone Regular Expression

Write a JavaScript program to clone a given regular expression.

  • Use new RegExp(), RegExp.prototype.source and RegExp.prototype.flags to clone the given regular expression.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2
// Define a function 'cloneRegExp' to create a clone of a regular expression.
const cloneRegExp = regExp => new RegExp(regExp.source, regExp.flags);

// Define a regular expression.
const regExp = /lorem ipsum/gi;
console.log(regExp); // Output the original regular expression.

// Create a clone of the original regular expression using 'cloneRegExp'.
const regExp2 = cloneRegExp(regExp);
console.log(regExp2); // Output the cloned regular expression.

Output:

{}
{}

Flowchart:

flowchart: Clone a given regular expression

Live Demo:

See the Pen javascript-basic-exercise-63-1 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript program that creates an exact clone of a given regular expression, preserving its flags.
  • Write a JavaScript function that accepts a regex and returns a new RegExp object with the same pattern and modifiers.
  • Write a JavaScript program that duplicates a regular expression and tests both the original and the clone for equivalence.

Go to:


PREV : Chain Asynchronous Functions.
NEXT : Get First Non-Null/Undefined Argument.

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.