V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Septembers
V2EX  ›  前端开发

一个优雅的 String.format 简单实现

  •  
  •   Septembers · 2015-05-14 09:59:12 +08:00 · 2648 次点击
    这是一个创建于 3262 天前的主题,其中的信息可能已经有所发展或是发生改变。
    // 这份代码片段基于Public Domain发布
    String.format = function(tpl) {
        var index = 1, items = arguments;
        return (tpl || '').replace(/{(\w*)}/g, function(match, p1) {
            return items[index++] || p1 || match;
        });
    };
    String.prototype.format = function() {
        var index = 0, items = arguments;
        return this.replace(/{(\w*)}/g, function(match, p1) {
            return items[index++] || p1 || match;
        });
    };
    
    > 'test{}test{}'.format()
    < "test{}test{}"
    > 'test{}test{2}'.format('1')
    < "test1test2"
    > 'test{}test{2}'.format('1', '3')
    < "test1test3"
    
    5 条回复    2015-05-15 01:05:06 +08:00
    est
        1
    est  
       2015-05-14 10:16:01 +08:00
    我还以为把 %03.3f 这种都实现了呢。
    YuJianrong
        2
    YuJianrong  
       2015-05-14 10:46:58 +08:00   ❤️ 1
    首先请不要修改内置类型的prototype……其次很快ES6的String template就可以用了……
    SoloCompany
        3
    SoloCompany  
       2015-05-14 11:07:45 +08:00   ❤️ 1
    qybei
        4
    qybei  
       2015-05-14 19:11:01 +08:00 via Android
    @YuJianrong 能说说不建议修改内置类型prototype的原因吗?
    YuJianrong
        5
    YuJianrong  
       2015-05-15 01:05:06 +08:00 via iPad
    @qybei 两个原因:
    1. 避免和其他库冲突,比如另一个库也手贱写了个String.format然后实现还不一样那两个必有一个工作不正常。
    2. 避免和未来的新标准冲突(比如mootools早期版本自己实现了function.bind和JSON对象,然后过了一段时间ES5标准里加入了不一样的实现……)

    所以唯一能接受的是为了在低版本浏览器上补足广泛接受的新特性而做的polyfill,比如补足IE8 的ES5支持的es5-shim,比如旧浏览器上用setTimeout模拟requestAnimationRefresh。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3246 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 12:40 · PVG 20:40 · LAX 05:40 · JFK 08:40
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.