1

I would like to format a string using positional placeholders in Javascript. For example, in Python I could do:

st1 = 'name'
st2 = 'javascript'
sentence = "My %s is %s." %(st1, st2)
print(sentence)

And I would get

My name is javascript.

as the output. Clearly it wouldn't work out in javascript (at least not exactly the same way), I know of using replace

var st1 = 'name';
var st2 = 'javascript';
var sentence = "My %s is %s".replace('%s', st1);
console.log(sentence);

But that would only replace the first occurrence of '%s'.

CyberLX
  • 225
  • 1
  • 5
  • 11
  • Why don't you do like that: `"My %s is %s".replace('%s', st1).replace('%s', st2);`? – R. Gadeev May 11 '17 at 01:58
  • 1
    http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format – sthiago May 11 '17 at 02:00
  • In ES6, you can use string interpolation. For more information: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Template_literals. – Eduardo Melo May 11 '17 at 02:09

1 Answers1

0
var st1 = 'name';
var st2 = 'javascript';
var sentence = `My ${st1} is ${st2}`;
console.log(sentence);

It will replace the two strings inside the sentence.

Eduardo Melo
  • 481
  • 1
  • 6
  • 19