-3

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.

Aatif
  • 11
  • 2
  • 1
    `.replace(/\{(\d+)}/, (m, $1) => obj[$1] || m)` – Tushar Sep 04 '17 at 06:23
  • 1
    prob. dupe: https://stackoverflow.com/questions/7975005/format-a-javascript-string-using-placeholders-and-an-object-of-substitutions – Nina Scholz Sep 04 '17 at 06:25
  • If {0} and {1} are fixed then you can use str.replace("{0}","value1"); and str.replace("{1}","value2"); Otherwise use regular expression. – Lalit Sep 04 '17 at 06:26
  • Possible duplicate of [Format a JavaScript string using placeholders and an object of substitutions?](https://stackoverflow.com/questions/7975005/format-a-javascript-string-using-placeholders-and-an-object-of-substitutions) – shaochuancs Sep 04 '17 at 06:27
  • Thanks but this does not work – Aatif Sep 04 '17 at 06:28
  • Possible duplicate of [JavaScript equivalent to printf/string.format](https://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format) – JJJ Sep 04 '17 at 06:30
  • 1
    @Aatif How does this not work? What goes wrong if you try? – Mr Lister Sep 04 '17 at 06:33

3 Answers3

0

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);
JSON Derulo
  • 9,780
  • 7
  • 39
  • 56
0

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.

Tushar
  • 85,780
  • 21
  • 159
  • 179
Jaimin
  • 171
  • 1
  • 1
  • 11
0

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392