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

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

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


当前回答

这是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

其他回答

export function stringFormat (str: string, ...args: string[]) {
     return args.reduce((acc, curr, i) => acc.replace(new RegExp("\\{" + i + "\\}", 'g'), curr), str);
}

当前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}}。所以要像恐惧噬菌体的建议那样同时进行替换。

这不是sprintf的精确复制;然而,它是类似的,并且更强大:https://github.com/anywhichway/stringformatter

使用此库的格式表达式采用嵌入式Javascript对象的形式,例如。

format("I have {number: {currency: "$", precision:2}}.",50.2); 

将返回“我有50.20美元”。

这很有趣,因为Stack Overflow实际上有自己的格式化函数,用于名为formatUnicorn的String原型。试试看!进入控制台并键入以下内容:

"Hello, {name}, are you feeling {adjective}?".formatUnicorn({name:"Gabriel", adjective: "OK"});

您将获得以下输出:

你好,加布里埃尔,你感觉还好吗?

您可以使用对象、数组和字符串作为参数!我得到了它的代码并对其进行了修改,以生成String.prototype.format的新版本:

String.prototype.formatUnicorn = String.prototype.formatUnicorn ||
function () {
    "use strict";
    var str = this.toString();
    if (arguments.length) {
        var t = typeof arguments[0];
        var key;
        var args = ("string" === t || "number" === t) ?
            Array.prototype.slice.call(arguments)
            : arguments[0];

        for (key in args) {
            str = str.replace(new RegExp("\\{" + key + "\\}", "gi"), args[key]);
        }
    }

    return str;
};

请注意,巧妙的Array.prototype.slice.call(arguments)调用——这意味着如果你输入的参数是字符串或数字,而不是一个JSON样式的对象,那么你几乎可以得到C#的String.Format行为。

"a{0}bcd{1}ef".formatUnicorn("FOO", "BAR"); // yields "aFOObcdBARef"

这是因为Array的切片会将参数中的任何内容强制到Array中,无论它最初是不是这样,并且关键字将是每个数组元素的索引(0,1,2…),该索引被强制到字符串中(例如,“0”,因此第一个正则表达式模式为“\\{0\\}”)。

整洁的

JavaScript中的sprintf()函数模拟为Vue过滤器和String.protype.format()扩展:

/**
 * Returns a formatted string.
 *
 * @param template
 * @param values
 * @return string
 */
String.format = function (template, ...values) {
    let i = -1;

    function callback(exp, p0, p1, p2, p3, p4) {
        if (exp === '%%') return '%';
        if (values[++i] === undefined) return undefined;

        exp = p2 ? parseInt(p2.substr(1)) : undefined;

        let base = p3 ? parseInt(p3.substr(1)) : undefined;
        let val;

        switch (p4) {
            case 's': val = values[i]; break;
            case 'c': val = values[i][0]; break;
            case 'f': val = parseFloat(values[i]).toFixed(exp); break;
            case 'p': val = parseFloat(values[i]).toPrecision(exp); break;
            case 'e': val = parseFloat(values[i]).toExponential(exp); break;
            case 'x': val = parseInt(values[i]).toString(base ? base : 16); break;
            case 'd': val = parseFloat(parseInt(values[i], base ? base : 10).toPrecision(exp)).toFixed(0); break;
        }
        val = typeof (val) == 'object' ? JSON.stringify(val) : val.toString(base);
        let sz = parseInt(p1); /* padding size */
        let ch = p1 && p1[0] === '0' ? '0' : ' '; /* isnull? */

        while (val.length < sz) val = p0 !== undefined ? val + ch : ch + val; /* isminus? */

        return val;
    }

    let regex = /%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd%])/g;

    return template.replace(regex, callback);
}

String.prototype.format = function() {
    return String.format(this, ...arguments);
}

const StringFormat = {
    install: (Vue, options) => {
        Vue.filter('format', function () {
            return String.format(...arguments);
        });
    },
};

export default StringFormat;

原始答案:JavaScript相当于printf/String.Format