0

I have this scenario where I get a string that might contain variables which are meant to be replaced with values from a json object

string = "Please input your %info1% in the %screen1% dialog and specify your %info2%. Thank you"
json = {
 info1: "name",
 info2: "age",
 screen1: "information"
}

I want to know if there is a way to avoid passing this to a function that should first check how many variables the string has (there are many strings to manipulate, which could have from 1 to 5 variables) using loops and stuff, and instead doing something like (will type it kind of pseudocode):

string.forEach(variable => replace variable with value from json)
return resulting string

Thanks!

freedomn-m
  • 27,664
  • 8
  • 35
  • 57
jprealini
  • 349
  • 4
  • 17
  • 4
    *json object* - this is not a thing. Please read [this SO answer](https://stackoverflow.com/questions/383692/what-is-json-and-what-is-it-used-for/383699#383699) – freedomn-m Aug 02 '23 at 19:12
  • 1
    Are template literals something you considered? https://www.typescriptlang.org/play?ssl=7&ssc=23&pln=6&pc=12#code/MYewdgzgLgBA3gSzAMxARgDQyagTFiYAJwFMSw0BfGAXngChsV0AuGAIjAEMBbE9jIxwhcbdlwDm-QTEKlyaMcKI8uUBOHb1K9UJFioVakgBNaMAAYAFADYkuEEkwAOAV1gBPEK6IwAJIjMVEwwUAAWTgFyZBTUJghcNiASMFxgZhDOJMAIyB4wXj7+gXiUFrrgECB2AHRJEgAUhqpQpgCUANxAA – Lesiak Aug 02 '23 at 19:12
  • What do you mean by "*avoid [to] first check how many variables the string has […] using loops and stuff*"? There is no way to avoid looping over the string at least once. – Bergi Aug 02 '23 at 19:22
  • It's a little hard to determine your requirements - eg "no functions" but `.forEach` (or similar construct is a "function"). This seems the perfect case of a function. You can do this with a simple `for .. in` to iterate the js object's properties: `for (var prop in obj) { s = s.replace(new RegExp("\%" + prop + "\%", "g"), obj[prop]); }` https://jsfiddle.net/wem2sc9v/1/ this may or may not suffice depending on the complexity of the original string (eg overlapping `%` placeholders). – freedomn-m Aug 02 '23 at 19:23

0 Answers0