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

2015-05-14 09:59:12 +08:00
 Septembers
// 这份代码片段基于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"
2653 次点击
所在节点    前端开发
5 条回复
est
2015-05-14 10:16:01 +08:00
我还以为把 %03.3f 这种都实现了呢。
YuJianrong
2015-05-14 10:46:58 +08:00
首先请不要修改内置类型的prototype……其次很快ES6的String template就可以用了……
SoloCompany
2015-05-14 11:07:45 +08:00
qybei
2015-05-14 19:11:01 +08:00
@YuJianrong 能说说不建议修改内置类型prototype的原因吗?
YuJianrong
2015-05-15 01:05:06 +08:00
@qybei 两个原因:
1. 避免和其他库冲突,比如另一个库也手贱写了个String.format然后实现还不一样那两个必有一个工作不正常。
2. 避免和未来的新标准冲突(比如mootools早期版本自己实现了function.bind和JSON对象,然后过了一段时间ES5标准里加入了不一样的实现……)

所以唯一能接受的是为了在低版本浏览器上补足广泛接受的新特性而做的polyfill,比如补足IE8 的ES5支持的es5-shim,比如旧浏览器上用setTimeout模拟requestAnimationRefresh。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/190956

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX