日期:2014-05-16  浏览次数:20314 次

extjs源码分析-013(String扩展)
//字符串替换
/*
var cls = 'my-class', text = 'Some text';
var s = String.format('<div class="{0}">{1}</div>', cls, text);
*/
Ext.applyIf(String, {
    format : function(format){
        var args = Ext.toArray(arguments, 1);
        return format.replace(/\{(\d+)\}/g, function(m, i){
            return args[i];
        });
    },
    //对字符串中的|\\进行转义输出
    escape : function(string) {
        return string.replace(/('|\\)/g, "\\$1");
    },
    //在字符串val左边插入size-val.length个指定字符串ch,如果ch未定义则默认为" "
    leftPad : function (val, size, ch) {
        var result = String(val);
        if(!ch) {
            ch = " ";
        }
        while (result.length < size) {
            result = ch + result;
        }
        return result;
    },
})


//俩个值切换,调用方式:sort = sort.toggle('ASC', 'DESC');
    String.prototype.toggle = function(value, other){
     return this == value ? other : value;
    };
    //去除字符串的空格 调用方式:var s = '  foo bar  ';_s = s.trim();
    String.prototype.trim = function(){
      var re = /^\s+|\s+$/g;
      return function(){ return this.replace(re, ""); };
    }()