<script>
    String.prototype.format = function (kwargs) {
        var ret = this.replace(/\{(\w+)\}/g, function (substring, args) { 
            return kwargs[args]
        });
    }
</script>

js 中是没有 format 这种格式化的方法的。

但是 因为字符串也是一个原型类,所有的方法都在  prototype中。 所以可以向这个里面添加一个 自定义的 format 方法。

  接收的参数因该是这样: {'age':18, 'name':'allan'}

  需要进行格式化的字符串:‘学生名:{name},年龄:{age}’

这样在使用 自定义的 format 方法时,

  this 就指的是  ‘{age}{name}’  。 使用replace进行替换, 第一个参数接收一个正则表达式,/\{(\w+)\}/g 表示全局匹配 大括号中的任意字母数字。

  第二个参数是,一个函数, 这个函数接收两个参数。每匹配成功一次就会将匹配的到的字符串交给后面的函数, 

  substring 就是  {age}  和 {name}, 这就是匹配到的内容。

  args 就是 age 和 name。 在匹配到的基础上 将其中 分组中的东西。

  拿到了   age 和 name,  就可以到 kwargs == {'age':18, 'name':'allan'}) kwargs 这个字典中,取出键所对应的值。 然后返回。

  这里的返回值, 就会交给 replace ,替换掉通过正则匹配到的 字符。

最终 :

  ‘学生名:{name},年龄:{age}’.format({'age':18, 'name':'allan'})  

得到的结果就会是:学生名:allan,年龄:18.   这样就达到了 python中 format的效果。

posted on 2019-05-21 17:01  rookiehbboy  阅读(1720)  评论(0编辑  收藏  举报