0

I have a string and array

var s1 = "hello %s, i am %d years old";
var s2 =[John,24];

Expected result:

s3 = hello John i am 24 years old

I want to save the output into another string. I'm able to display output in console

console.log(s1, ...s2)

But not able to store in other string. I tried many things like:

var s3 = s1.format(...s2)

Any suggestions?

TheDeveloper
  • 1,127
  • 1
  • 18
  • 55

2 Answers2

2

Unfortunately there is no string formatter available in JS, you'd have to write that manually like

 let i = 0;
 s3 = s1.replace(/%(s|d)/g, (_, type) => s2[i++]);
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
1

You could use the template string from ES6:

let anotherString = `Hello ${s2[0]}, I am ${s2[1]} years old`;

You could use this too:

String.prototype.format = function() {
    a = this;
    for (k in arguments) {
      a = a.replace("{" + k + "}", arguments[k])
    }
    return a
}

Usage:

let anotherString = '{0} {1}!'.format('Hello', 'Word');

Than those solutions I dont see any other way to do that.

Moussa Bistami
  • 929
  • 5
  • 15