How to insert a variable into regex in replace function with JavaScript

1 Answer

0 votes
let str = "CPP JavaScript CPP Python PHP CPP";
 
const word = "CPP";
const re = new RegExp(word, "gi");
  
str = str.replace(re, "C");
   
console.log(str);
 
 


                   
/*
run:
 
"C JavaScript C Python PHP C"
  
*/

 



answered May 22, 2022 by avibootz
...