带有关键字参数的Javascript字符串

Javascript strings with keyword parameters

本文关键字:Javascript 字符串 参数 关键字      更新时间:2023-09-26

我很想念ruby on rails的一个简单特性:字符串关键字参数,像这样:

"the key '%{key}' has a value of '%{value}'" % {:key => 'abc', :value => 5}

在javascript中,你必须对许多字符串求和,这使得代码很难看,很难编写。

有好的图书馆吗?我对sprint之类的东西不感兴趣。

String.prototype.format = function(obj) {
  return this.replace(/%'{([^}]+)'}/g,function(_,k){ return obj[k] });
};
"the key '%{key}' has a value of '%{value}'".format({ key:'abc', value:5 });

你可以创建一个基本的数组类型格式化器:

String.prototype.format = function(args) {
    var str = this,
        idxRx = new RegExp("{[0-9]+}", "g");
    return str.replace(idxRx, function(item) {
        var val = item.substring(1, item.length - 1),
            intVal = parseInt(val, 10),
            replace;
        replace = args[intVal];
        return replace;
    });
};

用法:

'{1} {0} and {2}!'.format(["collaborate", "Stop", "listen"])
// => 'Stop collaborate and listen!'