I have a JSON object that contains specific key-value pairs, and I am attempting to manipulate strings based on this object. Here is an example of the JSON structure:
{
"foo %s": "bar %s",
"Hello %s world %s.": "We have multiple %s %s."
}
My goal is to use this object to transform input strings using placeholders indicated by "%s". For instance:
foo bar
-> matchesfoo %s
-> should result inbar bar
Hello foo world bar.
-> matchesHello %s world %s.
-> should result inWe have multiple foo bar
Currently, I have implemented some code that partially achieves this functionality but has limitations. It only works for one "%s" at a time and requires spaces around it. Here is the code snippet:
let str = "input here";
let obj = {
"foo %s": "bar %s",
"Hello %s world %s.": "We have multiple %s %s."
},
pieces = str.split(" "),
output;
for (let j in pieces) { // loop through indices
let tempPieces = pieces.map(u => u); // create local array copy
tempPieces[j] = "%s"; // replace the index with %s
if (obj[tempPieces.join(" ")]) { // check if this pattern exists in the object
output = obj[tempPieces.join(" ")].replace("%s", pieces[j]); // combine the array and subtitute %s from the value
break;
}
}
Do you have any suggestions or improvements for this approach?