ruby on rails:strings キーワード パラメータにある次のようなシンプルな機能がとても恋しいです。
"the key '%{key}' has a value of '%{value}'" % {:key => 'abc', :value => 5}
JavaScript では、多くの文字列を合計する必要があり、コードが醜く、書きにくくなります。
これに適したライブラリはありますか?私はsprintfのようなものには興味がありません。
ruby on rails:strings キーワード パラメータにある次のようなシンプルな機能がとても恋しいです。
"the key '%{key}' has a value of '%{value}'" % {:key => 'abc', :value => 5}
JavaScript では、多くの文字列を合計する必要があり、コードが醜く、書きにくくなります。
これに適したライブラリはありますか?私はsprintfのようなものには興味がありません。
基本的な配列型フォーマッタを作成できます。
String.prototype.format = function(args) {
var str = this,
idxRx = new RegExp("{[0-9]+}", "g");
return str.replace(idxRx, function(item) {
var val = item.substring(1, item.length - 1),
intVal = parseInt(val, 10),
replace;
replace = args[intVal];
return replace;
});
};
使用法:
'{1} {0} and {2}!'.format(["collaborate", "Stop", "listen"])
// => 'Stop collaborate and listen!'