3

可能重复:
JavaScript 等价于 printf/string.format

我正在使用字典来保存网站中使用的所有文本,例如

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"
};

如何将“messagecount”写入 %s 所在的位置。

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 回答