The serve returns a JSON object
{
"key" : "Steps {0} of {1}"
}
How can I use {0} and {1} to replace with the values say "Steps 40 of 90" which I have in the front end object using javascript.
The serve returns a JSON object
{
"key" : "Steps {0} of {1}"
}
How can I use {0} and {1} to replace with the values say "Steps 40 of 90" which I have in the front end object using javascript.
Here is a working solution.
var obj = JSON.parse('{"key" : "Steps {0} of {1}"}');
var val1 = 40;
var val2 = 90;
var string = obj.key.replace('{0}', val1).replace('{1}', val2);
console.log(string);
First you fetch value of Key. You can use replace function like this.
var ans = str.replace("{0}","49(Your variable)")
It is normal string function.
You could take the JSON string and parse it, then replace with the suggested regular expression of Tushar with a global flag and use an array for replacements of the numbers.
var json = '{ "key": "Steps {0} of {1}" }',
object = JSON.parse(json),
replacements = [40, 90];
object.key = object.key.replace(/\{(\d+)}/g, (m, $1) => replacements[$1] || m);
console.log(object);
If you have no other replacements with the same numbers in the JSON string, you could replace the values directly in the string with
var json = '{ "key": "Steps {0} of {1}" }',
replacements = [40, 90];
json = json.replace(/\{(\d+)}/g, (m, $1) => replacements[$1] || m);
console.log(json);