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

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

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


当前回答

3种不同的javascript字符串格式

有三种不同的方法通过用变量值替换占位符来格式化字符串。

使用模板文本(反引号``)let name=“John”;假设年龄=30;//使用倒钩console.log(`${name}是${age}岁。`);//约翰30岁了。使用串联

let name=“John”;假设年龄=30;//使用串联console.log(name+'是'+age+'岁');//约翰30岁了。

创建自己的格式函数

String.prototype.format=函数(){var args=参数;返回this。replace(/{([0-9]+)}/g,函数(匹配,索引){//检查参数是否存在返回参数类型[index]==“undefined”?匹配:args[index];});};console.log(“{0}是{1}年前的。”.format(“John”,30));

其他回答

当前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.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}

bobjs可以做到这一点:

var sFormat = "My name is {0} and I am {1} years old."; 
var result = bob.string.formatString(sFormat, "Bob", 29); 
console.log(result); 
//output: 
//========== 
// My name is Bob and I am 29 years old. 

在typescript中,创建一个名为format.ts的文件,并导入您需要使用的任何格式。

// contents of format.ts

interface String {
  format(...args: any[]): string;
}

if (!String.prototype.format) {
  String.prototype.format = function() {
    let a = this;
    let b: any;
    // tslint:disable-next-line: forin
    for (b in arguments) {
      a = a.replace(/%[a-z]/, arguments[b]);
    }
    return a;
  };
}

要格式化字符串,请使用以下代码:

import './format';

console.log('Hello, %s!'.format('World'));

实例

String.prototype.format=函数(){设a=此;设b;for(参数中的b){a=a.replace(/%[a-z]/,自变量[b]);}返回a;};console.log(“您好,%s!”.format(“世界”));

下面是一个非常简短的函数,它执行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]