我正在寻找一个与C/PHP printf()或C#/Java程序员String.Format()(IFormatProvider for.NET)相当的JavaScript。

目前,我的基本要求是数字的千位分隔符格式,但处理大量组合(包括日期)的格式会很好。

我意识到Microsoft的Ajax库提供了String.Format()的一个版本,但我们不希望该框架的全部开销。


当前回答

使用Lodash,您可以获得模板功能:

使用ES模板文本分隔符作为“插入”分隔符。通过替换“interpole”分隔符禁用支持。

var compiled = _.template('hello ${ user }!');
compiled({ 'user': 'pebbles' });
// => 'hello pebbles!

其他回答

此方法适用于{0}、{1}和{}。

String.prototype.format = function format()
{                                                                                                               
  var msg = this;
  for(var i in arguments)
    msg = msg.replace(/\{\}/,arguments[i]).replace(new RegExp('\\{'+i+'\\}','g'),arguments[i]);
  return msg;
}

bobjs可以做到这一点:

var sFormat = "My name is {0} and I am {1} years old."; 
var result = bob.string.formatString(sFormat, "Bob", 29); 
console.log(result); 
//output: 
//========== 
// My name is Bob and I am 29 years old. 

我这里有一个稍长的JavaScript格式化程序。。。

可以通过多种方式设置格式:

String.format(输入,args0,arg1,…)String.format(输入,obj)“literal”.格式(arg0,arg1,…)“literal”.format(obj)

此外,如果您使用ObjectBase.prototype.format(例如使用DateJS),它将使用它。

示例。。。

var input = "numbered args ({0}-{1}-{2}-{3})";
console.log(String.format(input, "first", 2, new Date()));
//Outputs "numbered args (first-2-Thu May 31 2012...Time)-{3})"

console.log(input.format("first", 2, new Date()));
//Outputs "numbered args(first-2-Thu May 31 2012...Time)-{3})"

console.log(input.format(
    "object properties ({first}-{second}-{third:yyyy-MM-dd}-{fourth})"
    ,{
        'first':'first'
        ,'second':2
        ,'third':new Date() //assumes Date.prototype.format method
    }
));
//Outputs "object properties (first-2-2012-05-31-{3})"

我还使用了.asFormat作为别名,并进行了一些检测,以防已经存在字符串格式(例如使用MS Ajax Toolkit(我讨厌那个库))。

我有一个非常接近Peter的解决方案,但它涉及数字和对象情况。

if (!String.prototype.format) {
  String.prototype.format = function() {
    var args;
    args = arguments;
    if (args.length === 1 && args[0] !== null && typeof args[0] === 'object') {
      args = args[0];
    }
    return this.replace(/{([^}]*)}/g, function(match, key) {
      return (typeof args[key] !== "undefined" ? args[key] : match);
    });
  };
}

也许处理所有深度案件会更好,但对于我的需要来说,这很好。

"This is an example from {name}".format({name:"Blaine"});
"This is an example from {0}".format("Blaine");

PS:如果你在AngularJS这样的模板框架中使用翻译,这个函数非常酷:

<h1> {{('hello-message'|translate).format(user)}} <h1>
<h1> {{('hello-by-name'|translate).format( user ? user.name : 'You' )}} <h1>

en.json是什么样子的

{
    "hello-message": "Hello {name}, welcome.",
    "hello-by-name": "Hello {0}, welcome."
}

另一个建议是使用字符串模板:

const getPathDadosCidades = (id: string) =>  `/clientes/${id}`

const getPathDadosCidades = (id: string, role: string) =>  `/clientes/${id}/roles/${role}`