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

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

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


当前回答

String.prototype.format=函数(){var final=字符串(this);for(设i=0;i<arguments.length;i++){final=final.replace(“%s${i+1}”,参数[i])}return final |“”}console.log((“hello%s2 how%s3 you%s1”).format('hi','hello','how'));<h1 id=“text”></h1>

其他回答

好的,首先我们将设置一些要使用的变量:

    const date = new Date();
    
    const locale = 'en-us';
    
    const wDay   = date.toLocaleString(locale, {weekday: 'short'});
    const month  = date.toLocaleString(locale, {month: 'long'});
    const year   = date.toLocaleString(locale, {year: 'numeric'});
    const minute = date.toLocaleString(locale, {minute: 'numeric'});
    const [hour, ap] = date.toLocaleString(locale, {hour: 'numeric', hour12:true}).split(' ');
    
    let mDay = date.toLocaleString(locale, {day: 'numeric'});
    
    switch(mDay % 10)
    {
        case 1:  mDay += 'st'; break;
        case 2:  mDay += 'nd'; break;
        case 3:  mDay += 'rd'; break;
        default: mDay += 'th'; break;
    }

现在我们已经完成了所有这些,我们可以这样格式化字符串:

    const formatter = (...a) => `${a[0]}, the ${a[1]} of ${a[2]} ${a[3]} at ${a[4]}:${a[5]} ${a[6]}`;
    const formatted = formatter(wDay, mDay, month, year, hour, minute, ap);

我们甚至可以为“格式化程序”函数使用命名参数:

    const formatter = (wDay, mDay, month, year, hour, minute, ap) => `${wDay}, the ${mDay} of ${month} ${year} at ${hour}:${minute} ${ap}`;
    const formatted = formatter(wDay, mDay, month, year, hour, minute, ap);

如果您注意到,上面的JS模板都是回调的结果。如果上面的整段代码都封装在一个预期返回格式化日期的函数中,那么不难想象如何以相同的方式构造一个可以从外部传入的任意“格式化程序”函数。

tl;dr如果将模板文本放在回调中并使用args作为替换,则可以重用它们。

如果只需要使用%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

当前JavaScript

从上的ES6可以使用模板字符串:

let soMany = 10;
console.log(`This is ${soMany} times easier!`);
// "This is 10 times easier!"

详见下文Kim的回答。


较旧的答案

试试JavaScript的sprintf()。


如果你真的想自己做一个简单的格式化方法,不要连续替换,而是同时替换。

因为当先前替换的替换字符串也包含如下格式序列时,提到的大多数其他建议都会失败:

"{0}{1}".format("{1}", "{0}")

通常,您希望输出为{1}{0},但实际输出为{1}{1}}。所以要像恐惧噬菌体的建议那样同时进行替换。

我这里有一个稍长的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(我讨厌那个库))。

我用这个:

String.prototype.format = function() {
    var newStr = this, i = 0;
    while (/%s/.test(newStr))
        newStr = newStr.replace("%s", arguments[i++])

    return newStr;
}

然后我称之为:

"<h1>%s</h1><p>%s</p>".format("Header", "Just a test!");