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;
const regExp2 = cloneRegExp(regExp);

Sample Output:



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.

JavaScript: Tips of the Day

Chunks an array into n smaller arrays


const tips_chunkIntoN = (arr, n) => {
  const size = Math.ceil(arr.length / n);
  return Array.from({ length: n }, (v, i) =>
    arr.slice(i * size, i * size + size)
console.log(tips_chunkIntoN([1, 2, 3, 4, 5, 6, 7,8], 4));