【写一个自己的js库】 3.添加几个处理字符串的方法

1.生成重复的字符串

if(!String.repeat){
    String.prototype.repeat = function (count){
        return new Array(count + 1).join(this);
    }
}

2.去除开头和结尾的空字符

if(!String.trim){
    String.prototype.trim = function (){
        return this.replace(/^\s+|\s+$/g, '');
    }
}

3.将"-"格式的字符串变成驼峰形式的。这里replace函数的第二个参数是一个function,它接收三个参数,第一个是正则表达式匹配到的字符串,第二个是()匹配到的字符串,第三个是匹配到的字符串的索引。

function camelize(s){
        return s.replace(/-(\w)/g, function(regMatch, strMatch){
            return strMatch.toUpperCase();
        });
    }
    Lily['camelize'] = camelize;

 

posted @ 2015-08-28 21:42  lily white  阅读(162)  评论(0编辑  收藏  举报