0

I want to create a function like example (str, {msg: text, msg1: text2...}.

Assume that I have a string like: "hello world I'm {msg}"

And with JavaScript function, I want to call it like example (str, {msg: text}. Then this will give to me; hello world I'm text.

I know this can be handled with replace operation but replace operation doesn't look clear to me. Do you have other suggestions?

Sha
  • 921
  • 17
  • 46

1 Answers1

0

You can use string replace like below

function stringReplace(string, obj){
  Object.entries(obj).forEach(([template,value])=> {
     string = string.replace('{'+template+'}',value);
  });
  return string;
}

let str = "Hello from {test}";

console.log(stringReplace(str,{test: "world"}));
Dhananjai Pai
  • 5,914
  • 1
  • 10
  • 25