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

  • 相关阅读:
    系统设计实现
    反编译
    android layout analyze
    2016.7.20-notes
    如何认识刘昊然?
    leetcode-中等-队列-二叉树的层次遍历
    leetcode-简单-栈-逆波兰表达式
    leetcode-简单-栈-有效的括号
    队列-链式队列
    队列-循环队列-顺序存储
  • 原文地址:https://www.cnblogs.com/soymilk2019/p/15388984.html
Copyright © 2011-2022 走看看