JavaScript等同于printf / String.Format

JavaScript

十三LEY

2020-03-09

我正在寻找一种等效于C / PHP printf()或C#/ Java程序员String.Format()IFormatProvider适用于.NET)的JavaScript

我的基本要求是现在使用数字的千位分隔符格式,但是可以处理很多组合(包括日期)的东西会很好。

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

第216篇《JavaScript等同于printf / String.Format》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

17个回答
A十三 2020.03.09

我没有看到该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;
    });
};
Eva伽罗 2020.03.09

我们可以为Typescript 使用简单的轻量级String.Format字符串操作库。

String.Format():

var id = image.GetId()
String.Format("image_{0}.jpg", id)
output: "image_2db5da20-1c5d-4f1a-8fd4-b41e34c8c5b5.jpg";

说明符的字符串格式:

var value = String.Format("{0:L}", "APPLE"); //output "apple"

value = String.Format("{0:U}", "apple"); // output "APPLE"

value = String.Format("{0:d}", "2017-01-23 00:00"); //output "23.01.2017"


value = String.Format("{0:s}", "21.03.2017 22:15:01") //output "2017-03-21T22:15:01"

value = String.Format("{0:n}", 1000000);
//output "1.000.000"

value = String.Format("{0:00}", 1);
//output "01"

对象的字符串格式,包括说明符:

var fruit = new Fruit();
fruit.type = "apple";
fruit.color = "RED";
fruit.shippingDate = new Date(2018, 1, 1);
fruit.amount = 10000;

String.Format("the {type:U} is {color:L} shipped on {shippingDate:s} with an amount of {amount:n}", fruit);
// output: the APPLE is red shipped on 2018-01-01 with an amount of 10.000
蛋蛋L 2020.03.09

对于基本格式:

var template = jQuery.validator.format("{0} is not a valid value");
var result = template("abc");
Jnck 2020.03.09

您可以在http://www.webtoolkit.info/javascript-sprintf.html上找到JavaScript的“ sprintf”

樱A 2020.03.09

PHPJS项目写JavaScript实现的许多PHP的功能。由于PHP的sprintf()功能与C基本相同printf(),因此他们的JavaScript实现应能满足您的需求。

小小 2020.03.09

一个非常不同的版本,我喜欢的版本(此版本使用{xxx}令牌而不是{0}编号的参数,它具有更多的自说明性,并且更适合本地化):

String.prototype.format = function(tokens) {
  var formatted = this;
  for (var token in tokens)
    if (tokens.hasOwnProperty(token))
      formatted = formatted.replace(RegExp("{" + token + "}", "g"), tokens[token]);
  return formatted;
};

一个变化是:

  var formatted = l(this);

首先调用l()本地化函数。

Itachi伽罗 2020.03.09

我用这个:

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!");
梅小哥 2020.03.09

十分优雅:

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

Sam飞云 2020.03.09

如果要处理千位分隔符,则应真正使用JavaScript Number类中的toLocaleString(),因为它将格式化用户区域的字符串。

JavaScript Date类可以格式化本地化的日期和时间。

斯丁Jim 2020.03.09

我将添加自询问以来发现的发现:

可悲的是,似乎sprintf无法处理.NET的字符串格式之类的千位分隔符格式。

猪猪小小小哥 2020.03.09

为JavaScript使用了一个名为String.format的小型库支持大多数格式字符串功能(包括数字和日期的格式),并使用.NET语法。该脚本本身小于4 kB,因此不会产生太多开销。

梅蛋蛋 2020.03.09

+1 Zippo,除了函数体必须如下所示,否则它将在每次迭代后附加当前字符串:

String.prototype.format = function() {
    var formatted = this;
    for (var arg in arguments) {
        formatted = formatted.replace("{" + arg + "}", arguments[arg]);
    }
    return formatted;
};
西门小小 2020.03.09

对于Node.js用户,util.format它具有类似于printf的功能:

util.format("%s world", "Hello")
猪猪西门 2020.03.09

我使用以下简单功能:

String.prototype.format = function() {
    var formatted = this;
    for( var arg in arguments ) {
        formatted = formatted.replace("{" + arg + "}", arguments[arg]);
    }
    return formatted;
};

这与string.format非常相似:

"{0} is dead, but {1} is alive!".format("ASP", "ASP.NET")
Itachi猪猪 2020.03.09

JavaScript中的数字格式

我来到了这个问题页面,希望找到如何在JavaScript中格式化数字,而不引入另一个库。这是我发现的:

四舍五入浮点数

sprintf("%.2f", num)JavaScript中的等效项似乎是num.toFixed(2),格式num为2位小数,并四舍五入(但请参阅Math.round下面的@ ars265注释)。

(12.345).toFixed(2); // returns "12.35" (rounding!)
(12.3).toFixed(2); // returns "12.30" (zero padding)

指数形式

相当于sprintf("%.2e", num)IS num.toExponential(2)

(33333).toExponential(2); // "3.33e+4"

十六进制和其他基础

要在基数B中打印数字,请尝试num.toString(B)JavaScript支持从2到36的自动转换(此外,某些浏览器对base64编码的支持有限)。

(3735928559).toString(16); // to base 16: "deadbeef"
parseInt("deadbeef", 16); // from base 16: 3735928559

参考页

JS数字格式快速教程

MoFi的toFixed()参考页(带有toPrecision(),toExponential(),toLocaleString()等的链接)

Itachi阳光 2020.03.09

从ES6开始,您可以使用模板字符串

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

请注意,模板字符串用反引号 `代替,而不是(单引号)。

了解更多信息:

https://developers.google.com/web/updates/2015/01/ES6-Template-Strings

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/template_strings

注意:检查mozilla站点以找到支持的浏览器列表。

路易卡卡西 2020.03.09

从ES6开始,您可以使用模板字符串:

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

有关详细信息,请参见下面的Kim 答案


除此以外:

尝试sprintf()for JavaScript


如果您真的想自己做一个简单的格式化方法,请不要先后进行替换,而要同时进行。

Because most of the other proposals that are mentioned fail when a replace string of previous replacement does also contain a format sequence like this:

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

Normally you would expect the output to be {1}{0} but the actual output is {1}{1}. So do a simultaneously replacement instead like in fearphage’s suggestion.

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android