3

重複の可能性:
printf/string.formatと同等のJavaScript

私は辞書を使用して、次のようなWebサイトで使用されるすべてのテキストを保持しています。

var dict = {
  "text1": "this is my text"
};

javascript(jQuery)を使用してテキストを呼び出す、

$("#firstp").html(dict.text1);

そして、私のテキストの一部が静的ではないという問題を思い付きます。テキストにパラメータを書き込む必要があります。

あなたは100のメッセージを持っています

$("#firstp").html(dict.sometext+ messagecount + dict.sometext);

そしてこれはnoobishです

こんなもの欲しい

var dict = {
  "text1": "you have %s messages"
};

%sがある場所に「messagecount」を書き込むにはどうすればよいですか。

4

1 に答える 1

1

ライブラリがなくても、独自の簡単な文字列形式の関数を作成できます。

function format(str) {
    var args = [].slice.call(arguments, 1);
    return str.replace(/{(\d+)}/g, function(m, i) {
        return args[i] !== undefined ? args[i] : m;
    });
}

format("you have {0} messages", 10);
// >> "you have 10 messages"

Stringまたはオブジェクト経由:

String.prototype.format = function() {
    var args = [].slice.call(arguments);
    return this.replace(/{(\d+)}/g, function(m, i) {
        return args[i] !== undefined ? args[i] : m;
    });
};

"you have {0} messages in {1} posts".format(10, 5);
// >> "you have 10 messages in 5 posts"
于 2013-01-29T10:56:21.430 に答える