-2

I'm trying to make a code which finds {} sentences in string.

In example the string is:

var object = { username: "Matt", name: "Not Matt's server"};
var string = "Welcome to {name}, {username}!";

It finds {username} and {date} then replace them to values in other object, so the value should:

"Welcome to Not Matt's server, Matt!";
Wiktor Stribiżew
  • 561,645
  • 34
  • 376
  • 476
Ben Mert
  • 61
  • 5

2 Answers2

0

You can use regular expression and String.replace() method to replace the string. You can also use String.replaceAll() if you want to replace more than 1 occurrence.

var data = { username: "Matt", name: "Not Matt's server"};
var string = "Welcome to {name}, {username}!";


Object.keys(data).forEach(key => {

  const re = new RegExp('{' + key + '}',"g");
  string = string.replace(re, data[key])
  
})

console.log(string)
Harun Yilmaz
  • 7,773
  • 3
  • 24
  • 33
  • What would happen if one of the properties in `data` contains a regex meta character? – Andreas Louv Jan 19 '21 at 08:17
  • @andlrc You're right, this can lead to an unexpected error. I think escaping the `data[key]` before calling `replace` method could help. This thread may help in that case: https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript/3561711 – Harun Yilmaz Jan 19 '21 at 08:31
0

I would solve it by making a generic regex that matches keys between { and } and then lookup the value with the extracted key:

var object = { username: "Matt", name: "Not Matt's server"};
var string = "Welcome to {name}, {username}!";
string.replace(/\{(\w+)\}/g, (_, key) => object[key]);

This have the flaws of replacing an unknown key with undefined.

Andreas Louv
  • 44,338
  • 13
  • 91
  • 116