0

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.

Adarsh Hegde
  • 623
  • 2
  • 7
  • 19

1 Answers1

2

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);
Vivek
  • 1,465
  • 14
  • 29
  • 1
    Thank you, it works, could you please explain what was the cause of it not working? – Adarsh Hegde Jun 02 '18 at 14:51
  • 1
    @AdarshHegde `replace` method is not replacing in-place of string, you have to re-assign it back to `temp` - [reference](https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string-in-javascript) – Vivek Jun 02 '18 at 14:53