在此之前,我们已经完成了4个方法:
trimLeft, trimRight, trim, capitalize
本文,我们扩展驼峰式与下划线转化这两个对称的方法
camelize: 把空格,下划线,中横线后面的首字母大写.
dasherize: 把空格后面的大写字母,大写字母,下划线后面的大写字母,变成 中横线 + 对应的小写字母:
如: MozBorderRadius 变成 -moz-border-radius
; (function (window, undefined) {
function init(obj, s) {
if (s !== null && s !== undefined) {
if (typeof s === 'string') {
obj.s = s;
} else {
obj.s = s.toString();
}
} else {
obj.s = s;
}
} function G(s) {
init(this, s);
} function GhostWu(s) {
return new G(s);
} var sProto = String.prototype;
G.prototype = {
constructor: G,
capitalize: function () {
return new this.constructor(this.s.slice(0, 1).toUpperCase() + this.s.substring(1).toLowerCase());
},
trimLeft: function () {
var s;
if (sProto.trimLeft === 'undefined')
s = this.s.trimLeft();
else
s = this.s.replace(/^\s+/g, '');
return new this.constructor(s);
},
trimRight: function () {
var s;
if (sProto.trimRight === 'undefined')
s = this.s.trimRight();
else
s = this.s.replace(/\s+$/g, '');
return new this.constructor(s);
},
trim: function () {
var s;
if (typeof sProto.trim === 'undefined') {
s = this.s.replace(/^\s+|\s+$/g, '');
} else {
s = this.s.trim();
}
return new this.constructor(s);
},
camelize : function () {
var s = this.trim().s.replace(/(\-|_|\s)+(.)?/g, function ( s0, s1, s2 ) {
return ( s2 ? s2.toUpperCase() : '' );
});
return new this.constructor(s);
},
dasherize : function(){
var s = this.trim().s.replace(/[_\s]+/g, '-').replace(/([A-Z])/g, '-$1').replace(/-+/g, '-').toLowerCase();
return new this.constructor(s);
}
}; window.G = GhostWu;
})(window, undefined);
console.log( G( 'ghost wu tell you how to learn js').camelize().s );//ghostWuTellYouHowToLearnJsconsole.log( G( 'ghost-wu-tell you how to learn js').camelize().s );//ghostWuTellYouHowToLearnJsconsole.log( G( 'ghost_wu_tell you how to learn js').camelize().s );//ghostWuTellYouHowToLearnJsconsole.log( G( '-moz-border-radius' ).camelize().s );//MozBorderRadiusconsole.log( G( 'MozBorderRadius' ).dasherize().s ); //-moz-border-radiusconsole.log( G( 'backgroundColor' ).dasherize().s ); //background-colorconsole.log( G( 'background color' ).dasherize().s ); //background-color