zoukankan      html  css  js  c++  java
  • JavaScript: 如何使用 format 格式化字符串

    在 Java 等编程语言中有 String.format 方法用来组装字符串,非常方便。

    而 JavaScript 中好像只能是通过加号组装:

    var s = "Hello " + " World"

    有类似 String.format 的函数吗?有,但要自己实现。

    方式1:使用ES6

    在最新的 Chrome 等浏览器中已经支持 ES6 了。

    var name = 'letian'
    var s = `Hello ${name}`
    console.log(s)

    方法2:在 String 原型中增加 format 函数

    String.prototype.format = function() {
        var formatted = this;
        for( var arg in arguments ) {
            formatted = formatted.replace("{" + arg + "}", arguments[arg]);
        }
        return formatted;
    };
    
    var s = '你好 {0} {1}'.formar('value1', 123)
    console.log(s)

    运行结果:

    你好 value1 123

    但是上面这个实现有 bug,比如 '{0} {1}'.format('{1}', '{0}') 的结果是 {0} {1},这个和预期的 {1} {0} 不一致。

    修复如下:

    if (!String.prototype.format) {
      String.prototype.format = function() {
        var args = arguments;
        return this.replace(/{(d+)}/g, function(match, number) { 
          return typeof args[number] != 'undefined'
            ? args[number]
            : match
          ;
        });
      };
    }

    如果不想在字符串后面加.format,可以用 String.format 方法,那么可以用下面的实现:

    if (!String.format) {
      String.format = function(format) {
        var args = Array.prototype.slice.call(arguments, 1);
        return format.replace(/{(d+)}/g, function(match, number) { 
          return typeof args[number] != 'undefined'
            ? args[number] 
            : match
          ;
        });
      };
    }
    使用示例: String.format('{0}', 'Hello')。

    方法3: sprintf.js 库

    见 https://github.com/alexei/sprintf.js 。

    参考

    原文:https://www.letianbiji.com/web-front-end/js-string-format.html

  • 相关阅读:
    JS使用 popstate 事件监听物理返回键
    JQ判断div是否隐藏
    SQL Server DATEDIFF() 函数
    取消a或input标签聚焦后出现虚线框
    C#定时任务
    C# 保留N位小数
    C#打印单据
    SQL语句创建函数
    SVN检出新项目
    解决jQuery的toggle()的自动触发问题
  • 原文地址:https://www.cnblogs.com/soymilk2019/p/15388984.html
Copyright © 2011-2022 走看看