Search code examples
javascriptarraysreplacereplaceall

failing to replace text according to a predefined list


I'm trying to make a function which replaces specific strings within a set of code according to a pre defined list of search words and what it should be replaced with,

render = (data,list) => {
let temp = data;
  for(let i in list){
    temp.split(i).join(list[i]);
   //temp.replace(new RegExp(i, 'g'), list[i]); even this doesn't work
  }
return temp;
}
let test = render("<h1>a1</h1>",
 { "a1" : "Hello World" });

I don't see any errors, it just doesn't replace anything and returns the original data as it is, if I use the code used for the replacement separately and manually place in the values in the regExp or split join functions, it works fine..

//edit

The Expected input and output should be,

let temp = "<h1> $1 </h1>";
console.log( render(test, { "$1":"Hello World" } ) );

This is supposed to output,

<h1> Hello World </h1>

but I instead get

<h1> $1 </h1>

as it is.


Solution

  • Here's solution -

    render = (data, list) => {
      let temp = data;
      for (let i in list) {
        temp = temp.replace(new RegExp(i, 'g'), list[i]);
      }
      return temp;
    }
    let test = render("<h1>a1</h1>", {
      "a1": "Hello World"
    });
    
    console.log(test);