V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
Septembers

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

  •  
  •   Septembers · May 14, 2015 · 3440 views
    This topic created in 4013 days ago, the information mentioned may be changed or developed.
    // 这份代码片段基于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 replies    2015-05-15 01:05:06 +08:00
    est
        1
    est  
       May 14, 2015
    我还以为把 %03.3f 这种都实现了呢。
    YuJianrong
        2
    YuJianrong  
       May 14, 2015   ❤️ 1
    首先请不要修改内置类型的prototype……其次很快ES6的String template就可以用了……
    SoloCompany
        3
    SoloCompany  
       May 14, 2015   ❤️ 1
    qybei
        4
    qybei  
       May 14, 2015 via Android
    @YuJianrong 能说说不建议修改内置类型prototype的原因吗?
    YuJianrong
        5
    YuJianrong  
       May 15, 2015 via iPad
    @qybei 两个原因:
    1. 避免和其他库冲突,比如另一个库也手贱写了个String.format然后实现还不一样那两个必有一个工作不正常。
    2. 避免和未来的新标准冲突(比如mootools早期版本自己实现了function.bind和JSON对象,然后过了一段时间ES5标准里加入了不一样的实现……)

    所以唯一能接受的是为了在低版本浏览器上补足广泛接受的新特性而做的polyfill,比如补足IE8 的ES5支持的es5-shim,比如旧浏览器上用setTimeout模拟requestAnimationRefresh。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5394 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 42ms · UTC 08:05 · PVG 16:05 · LAX 01:05 · JFK 04:05
    ♥ Do have faith in what you're doing.