是否有相当于rubys"#{}"序列的JavaScript?

Bri*_*hrs 2 javascript ruby

有没有比使用字符串连接更好的方法来构建JavaScript中的字符串?

它会使我的代码更清晰,如果我可以做像ruby的东西,你可以在字符串中扩展变量,而不是做很多"foo"+ bar +"baz".

pyl*_*ver 7

String.prototype.format = function() {
  var args = arguments;
  return this.replace(/{(\d+)}/g, function(match, number) { 
    return typeof args[number] != 'undefined'
      ? args[number]
      : match
    ;
  });
};


console.log("{0} bar {1}.".format("foo","baz"));
Run Code Online (Sandbox Code Playgroud)

会产生:

"foo bar baz"