有没有比使用字符串连接更好的方法来构建JavaScript中的字符串?
它会使我的代码更清晰,如果我可以做像ruby的东西,你可以在字符串中扩展变量,而不是做很多"foo"+ bar +"baz".
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"