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.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to chain asynchronous functions.
Next: Write a JavaScript program to get the first non-null / undefined argument.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/javascript-exercises/fundamental/javascript-fundamental-exercise-63.php