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

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

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


当前回答

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

util.format("%s world", "Hello")

其他回答

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

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

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

util.format("%s world", "Hello")

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 getPathDadosCidades = (id: string) =>  `/clientes/${id}`

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