PythonからJavaScriptへ

戸惑ったことの忘備録

JavaScriptにはformat関数が無い!

replaceメソッドを使う

置換したいものが増えると煩雑になってくる。

x = 10;
y = 70;
t = "x={0}, y={1}".replace("{0}", x).replace("{1}", y);
console.log(t);

自分で作る

自分でStringクラスにprototype宣言で、メソッド(format)を追加する方法がある。シンプルで使いやすい。

PythonやC#などにあるformatメソッドをJavaScriptで使いたい

/*
 * pythonやC#のformatメソッド的な機能を実現
 */
String.prototype.format = function(){
	let formatted = this;
	for(let arg in arguments){
		formatted = formatted.replace("{" + arg + "}", arguments[arg]);
	}
	return formatted;
};

x = 10;
y = 70;
t = "x={0}, y={1}".format(x, y)
console.log(t);

コメントする