我正在寻找一个良好的JavaScript等价物来替代C/PHP中的printf()
或对于C#/Java程序员,String.Format()
(.NET使用 IFormatProvider
)。
我的基本要求是数字的千位分隔符格式,但能处理许多组合(包括日期)的东西会更好。
我意识到微软的Ajax库提供了一个版本的String.Format()
,但我们不想要整个框架的开销。
我正在寻找一个良好的JavaScript等价物来替代C/PHP中的printf()
或对于C#/Java程序员,String.Format()
(.NET使用 IFormatProvider
)。
我的基本要求是数字的千位分隔符格式,但能处理许多组合(包括日期)的东西会更好。
我意识到微软的Ajax库提供了一个版本的String.Format()
,但我们不想要整个框架的开销。
我在列表中没有看到pyformat,所以我想加上它:
console.log(pyformat( 'The {} {} jumped over the {}'
, ['brown' ,'fox' ,'foobar']
))
console.log(pyformat('The {0} {1} jumped over the {1}'
, ['brown' ,'fox' ,'foobar']
))
console.log(pyformat('The {color} {animal} jumped over the {thing}'
, [] ,{color: 'brown' ,animal: 'fox' ,thing: 'foobaz'}
))
另一个建议是使用字符串模板:
const getPathDadosCidades = (id: string) => `/clientes/${id}`
const getPathDadosCidades = (id: string, role: string) => `/clientes/${id}/roles/${role}`
/**
* Format string by replacing placeholders with value from element with
* corresponsing index in `replacementArray`.
* Replaces are made simultaneously, so that replacement values like
* '{1}' will not mess up the function.
*
* Example 1:
* ('{2} {1} {0}', ['three', 'two' ,'one']) -> 'one two three'
*
* Example 2:
* ('{0}{1}', ['{1}', '{0}']) -> '{1}{0}'
*/
function stringFormat(formatString, replacementArray) {
return formatString.replace(
/\{(\d+)\}/g, // Matches placeholders, e.g. '{1}'
function formatStringReplacer(match, placeholderIndex) {
// Convert String to Number
placeholderIndex = Number(placeholderIndex);
// Make sure that index is within replacement array bounds
if (placeholderIndex < 0 ||
placeholderIndex > replacementArray.length - 1
) {
return placeholderIndex;
}
// Replace placeholder with value from replacement array
return replacementArray[placeholderIndex];
}
);
}
用于 jQuery.ajax() 成功函数。只传递单个参数,并将该对象的属性替换为 {propertyName}:
String.prototype.format = function () {
var formatted = this;
for (var prop in arguments[0]) {
var regexp = new RegExp('\\{' + prop + '\\}', 'gi');
formatted = formatted.replace(regexp, arguments[0][prop]);
}
return formatted;
};
例子:
var userInfo = ("Email: {Email} - Phone: {Phone}").format({ Email: "someone@somewhere.com", Phone: "123-123-1234" });
我没有看到String.format
的变体:
String.format = function (string) {
var args = Array.prototype.slice.call(arguments, 1, arguments.length);
return string.replace(/{(\d+)}/g, function (match, number) {
return typeof args[number] != "undefined" ? args[number] : match;
});
};
String.prototype.format = function(){
var _args = arguments
Array.prototype.unshift.apply(_args,[this])
return sprintf.apply(undefined,_args)
}
// this gives you:
"{%1$s}{%2$s}".format("1", "0")
// {1}{0}
arg
函数:
/**
* Qt stil arg()
* var scr = "<div id='%1' class='%2'></div>".arg("mydiv").arg("mydivClass");
*/
String.prototype.arg = function() {
var signIndex = this.indexOf("%");
var result = this;
if (signIndex > -1 && arguments.length > 0) {
var argNumber = this.charAt(signIndex + 1);
var _arg = "%"+argNumber;
var argCount = this.split(_arg);
for (var itemIndex = 0; itemIndex < argCount.length; itemIndex++) {
result = result.replace(_arg, arguments[0]);
}
}
return result;
}
function L(...values)
{
// Replace each '@', starting with the text in the first arg
console.log(values.reduce(function(str,arg) {return str.replace(/@/,arg)}));
} // L
这是一个测试:
let a=[1,2,3];
L('a: [@]',a);
输出类似于:a=[1,2,3]
simple_format(1234567,"$ ###,###,###.##")
"$ 12,345.67"
simple_format(1234567,"### ### ###,## pln")
"12 345,67 pln"
我相信这对用户来说很容易理解,也很容易实现:
function simple_format(integer,format){
var text = "";
for(var i=format.length;i--;){
if(format[i]=='#'){
text = (integer%10) + text;
integer=Math.floor(integer/10);
if(integer==0){
return format.substr(0,i).replace(/#(.*#)?/,"")+text;
}
}else{
text = format[i] + text;
}
}
return text;
}
String.padStart
。 (请参见https://dev59.com/jXE85IYBdhLWcg3wnU-p) - Nor.Z