LoginSignup
6
4

More than 5 years have passed since last update.

JavaScriptで.NetライクなString.Format()

Posted at

ES6のテンプレート構文を使えないブラウザ(IE11とか)でも、似たような事がしたいとき用のメモ。
C#とかVB.NetのString.Format()みたいな使い方が可能。

console.log("aaa,{0},ccc,{1},eee".format("bbb","ddd"));
// "aaa,bbb,ccc,ddd,eee"

// フォーマットを変数に入れておくことも出来る分、テンプレートリテラルより扱いやすいかも
let str = "aaa,{0},ccc,{1},eee";
str.format("bbb","ddd");
// "aaa,bbb,ccc,ddd,eee"

事前準備として、以下のコードをでString.format()メソッドを作成しておく。

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

参考元:JavaScript equivalent to printf/String.Format

6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4