我正在寻找一个与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()的一个版本,但我们不希望该框架的全部开销。
当前回答
/**
* 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];
}
);
}
其他回答
jsxt、Zippo
此选项更适合。
String.prototype.format = function() {
var formatted = this;
for (var i = 0; i < arguments.length; i++) {
var regexp = new RegExp('\\{'+i+'\\}', 'gi');
formatted = formatted.replace(regexp, arguments[i]);
}
return formatted;
};
使用此选项,我可以替换如下字符串:
'The {0} is dead. Don\'t code {0}. Code {1} that is open source!'.format('ASP', 'PHP');
使用您的代码,不会替换第二个{0}。;)
如果只需要使用%s说明符格式化字符串
function _sprintf(message){
const regexp = RegExp('%s','g');
let match;
let index = 1;
while((match = regexp.exec(message)) !== null) {
let replacement = arguments[index];
if (replacement) {
let messageToArray = message.split('');
messageToArray.splice(match.index, regexp.lastIndex - match.index, replacement);
message = messageToArray.join('');
index++;
} else {
break;
}
}
return message;
}
_sprintf("my name is %s, my age is %s", "bob", 50); // my name is bob, my age is 50
非常优雅:
String.prototype.format = function (){
var args = arguments;
return this.replace(/\{\{|\}\}|\{(\d+)\}/g, function (curlyBrack, index) {
return ((curlyBrack == "{{") ? "{" : ((curlyBrack == "}}") ? "}" : args[index]));
});
};
// Usage:
"{0}{1}".format("{1}", "{0}")
信贷转到(断开链接)https://gist.github.com/0i0/1519811
使用Lodash,您可以获得模板功能:
使用ES模板文本分隔符作为“插入”分隔符。通过替换“interpole”分隔符禁用支持。
var compiled = _.template('hello ${ user }!');
compiled({ 'user': 'pebbles' });
// => 'hello pebbles!
我需要更进一步的解决方案。
我可以重用一个模板,不仅在声明中生成字符串,而且在执行时间的随机时间生成字符串。
所以我遇到了这个夹具:
class Texplate{
constructor(...args){
this.data = args;
}
apply(...args){
var text = "";
var i = 0, j = 0, n = this.data.length, m = args.length;
for(;i < n && j < m; i++, j++){
text += this.data[i] + args[j];
}
for (; i < n; i++){
text += this.data[i];
}
for (; j < m; j++){
text += args[j];
}
return text;
}
}
这允许创建一个文本模板,该模板在内部用作数组合并算法,从构造函数中定义的文本数组开始。
使用示例:
var Textplate example = new Texplate("Hello, ", "!");
console.log(example.apply("Frank"));
console.log(example.apply("Mary"));
console.log(example.apply());
console.log(example.apply("Frank", " Have a good day!"));