使用JavaScript实现字符串格式化

使用JavaScript实现字符串格式化

    String.prototype.format = function (kwargs) {
        /*
        hello-{n}-{m}
        {'n':'word','m':'!'}
        */
        var res = this.replace(/\{(\w+)\}/g,function (groups,group) {
              return kwargs[group]
        });
        return res
    };
    var info = 'hello-{n}-{m}';
    var dicts = {'n':'word','m':'!'};
    var ret = info.format(dicts);
    console.log(ret)

 

posted @ 2018-11-30 23:03  梦中琴歌  阅读(296)  评论(0编辑  收藏  举报