RegExp with replace and replaceAll methods Learn JavaScript how to apply Regular Expressions

The replace() method returns a new version of the original string with the pattern matched values being replaced by the new string value. RegExp can be used to set the pattern to be matched, if the pattern is a string value only the first occurrence of the matched results will be replaced.

Using a string as the first argument in the replace() method, will match the result in the string and return a new string value with the updated pattern replaced with the new string value.

replace() and replaceAll() methods

const txtArea = document.querySelector(‘textarea’);

const btn = document.querySelector(‘button’);

const res = document.querySelector(‘.results’);

const str1 = ‘Hello love World.  I love JavaScript!’;

const rexg = RegExp(‘love’,’g’);

const reg = /love/gi;

const reg1 = /love/g;

txtArea.value = str1;


   const str =  txtArea.value;

   const str2 = str.replace(reg,’enjoy’);

   const str3 = str.replaceAll(reg1,’fun’);

   const str4 = str.replaceAll(‘love’,’fun’);

   const str5 = str.replace(‘love’,’like’);

   res.innerHTML = str3;