JavaScript对应于printf/String.Format的函数

2411

我正在寻找一个良好的JavaScript等价物来替代C/PHP中的printf()或对于C#/Java程序员,String.Format()(.NET使用 IFormatProvider)。

我的基本要求是数字的千位分隔符格式,但能处理许多组合(包括日期)的东西会更好。

我意识到微软的Ajax库提供了一个版本的String.Format(),但我们不想要整个框架的开销。


4
除了下面众多优秀的回答,您或许也想看看这个链接:https://dev59.com/pXNA5IYBdhLWcg3wPbSe#2648463,在我看来,这是解决此问题最高效的方法。 - Annie
3
我写了一个简单的程序,使用类C语言的printf语法。 - Braden Best
var search = [$scope.dog, "1"]; var url = vsprintf("http://earth/Services/dogSearch.svc/FindMe/%s/%s", search); ***对于Node,您可以通过“npm install sprintf-js”获取您的模块。 - Jenna Leaf
5
这里的大多数答案都令人失望。printf和String.Format不仅仅是简单的模板,而且问题特别提到了千位分隔符,这是简单模板解决方案都无法处理的。 - blm
除了“模板字符串”之外,人们可能还在寻找String.padStart。 (请参见https://dev59.com/jXE85IYBdhLWcg3wnU-p) - Nor.Z
显示剩余3条评论
61个回答

3

我在列表中没有看到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'}
                ))

3

另一个建议是使用字符串模板:

const getPathDadosCidades = (id: string) =>  `/clientes/${id}`

const getPathDadosCidades = (id: string, role: string) =>  `/clientes/${id}/roles/${role}`

谢谢,将这个放入lambda中的想法让我省了很多麻烦! - David Schmitt

2
/**
 * 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];
        }
    );
}

2

用于 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" });

2

我没有看到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;
    });
};

2
使用sprintf.js - 可以制作一个漂亮的格式化工具。
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}

1

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;
}

1
这是一个非常简短的函数,它执行printf的子集并在开发者控制台中显示结果:
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]


1
我需要一个函数,可以按照用户喜欢的方式格式化价格(以分为单位),而棘手的部分是格式由用户指定 - 我不希望我的用户理解类似printf的语法或正则表达式等。我的解决方案与Basic中使用的解决方案有些相似,因此用户只需用#标记数字的位置,例如:
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;
}

1

jQuery Globalize项目中还有Globalize.format,它是jQuery UI的官方全球化服务。当您需要文化感知格式化时,它非常好用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接