w3resource

JavaScript: Clone a given regular expression

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

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 
const cloneRegExp = regExp => new RegExp(regExp.source, regExp.flags);
const regExp = /lorem ipsum/gi;
console.log(regExp);
const regExp2 = cloneRegExp(regExp);
console.log(regExp2);

Sample 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.



Follow us on Facebook and Twitter for latest update.