我正在寻找一个与C/PHP printf()或C#/Java程序员String.Format()(IFormatProvider for.NET)相当的JavaScript。
目前,我的基本要求是数字的千位分隔符格式,但处理大量组合(包括日期)的格式会很好。
我意识到Microsoft的Ajax库提供了String.Format()的一个版本,但我们不希望该框架的全部开销。
我正在寻找一个与C/PHP printf()或C#/Java程序员String.Format()(IFormatProvider for.NET)相当的JavaScript。
目前,我的基本要求是数字的千位分隔符格式,但处理大量组合(包括日期)的格式会很好。
我意识到Microsoft的Ajax库提供了String.Format()的一个版本,但我们不希望该框架的全部开销。
当前回答
对于Node.js用户,util.format具有类似printf的功能:
util.format("%s world", "Hello")
其他回答
为了防止有人需要一个功能来防止污染全球范围,下面是一个功能:
function _format (str, arr) {
return str.replace(/{(\d+)}/g, function (match, number) {
return typeof arr[number] != 'undefined' ? arr[number] : match;
});
};
我使用这个简单的函数:
String.prototype.format = function() {
var formatted = this;
for( var arg in arguments ) {
formatted = formatted.replace("{" + arg + "}", arguments[arg]);
}
return formatted;
};
这与string.format非常相似:
"{0} is dead, but {1} is alive!".format("ASP", "ASP.NET")
我开始将Java String.format(实际上是新的Formatter().format))移植到javascript。初始版本位于:
https://github.com/RobAu/javascript.string.format
您可以简单地添加javscript并调用StringFormat.format(“%.2f”,[2.4]);等
请注意,尚未完成,但欢迎反馈:)
这是https://stackoverflow.com/a/4673436/1258486对于CoffeeScript。
https://gist.github.com/eces/5669361
if String.prototype.format is undefined
String.prototype.format = () ->
_arguments = arguments
this.replace /{(\d+)}/g, (match, number) ->
if typeof _arguments[number] isnt 'undefined' then _arguments[number] else match
3种不同的javascript字符串格式
有三种不同的方法通过用变量值替换占位符来格式化字符串。
使用模板文本(反引号``)let name=“John”;假设年龄=30;//使用倒钩console.log(`${name}是${age}岁。`);//约翰30岁了。使用串联
let name=“John”;假设年龄=30;//使用串联console.log(name+'是'+age+'岁');//约翰30岁了。
创建自己的格式函数
String.prototype.format=函数(){var args=参数;返回this。replace(/{([0-9]+)}/g,函数(匹配,索引){//检查参数是否存在返回参数类型[index]==“undefined”?匹配:args[index];});};console.log(“{0}是{1}年前的。”.format(“John”,30));