Alex
Alex

Reputation: 143

Replace words in a string based on the rules

I have a string like this

"Hello {{firstName}}, this is {{senderName}}."

The rules

rules = {
  firstName: "Alex",
  senderName: "Tracy"
}

Expect result

"Hello Alex, this is Tracy."

I want a generic function to convert any string with the corresponding rules to a new string.

Another example:

let array = "Hello {{firstName}} {{lastName}}, this is {{senderName}}."
rules = {
  firstName: "Alex",
  lastName: "James",
  senderName: "Tracy"
}
expectedResult = "Hello Alex James, this is Tracy." 

Any help wound be appreciated.

Upvotes: 0

Views: 75

Answers (2)

antonku
antonku

Reputation: 7665

You can take advantage of a replacement function that can be passed to String.prototype.replace:

const str = "Hello {{firstName}} {{lastName}}, this is {{senderName}}."
const mapping = {
  firstName: "Alex",
  lastName: "James",
  senderName: "Tracy"
}
const compile = (template, rules) => template.replace(/{{(.+?)}}/g, (match, group) => rules[group]);

const result = compile(str, mapping);
console.log(result);

Upvotes: 1

suresh bambhaniya
suresh bambhaniya

Reputation: 1687

you can loop through and replace all variable with value

    function resolve_str(rules,str){
      for(let i in rules){
        str = str.replace("{{"+i+"}}", rules[i]);
      }
      return str;
    }

    let array = "Hello {{firstName}} {{lastName}}, this is {{senderName}}."
    rules = {
      firstName: "Alex",
      lastName: "James",
      senderName: "Tracy"
    }

    console.log(resolve_str(rules,array));

Upvotes: 2

Related Questions