虽然js String对象已经提供像slice、replace、indexOf和substring等方法,但在实际项目应用中会对其进行扩展,以达到实用、方便目的。注释很详细,废话少说,代码如下:
1 /** 2 *字符串-格式化 3 */ 4 String.prototype.format = function(){ 5 var args = arguments;//获取函数传递参数数组,以便在replace回调函数内使用 6 var regex = /\{(\d+)\}/g;//匹配并捕获所有 形如:{数字} 字串 7 return this.replace(regex,function(m,i){//参数=匹配子串+第几次匹配+匹配字串位置+源字符串 8 return args[i]; 9 }); 10 } 11 /** 12 *字符串-去掉前后空白字符 13 */ 14 String.prototype.trim = function(){ 15 return this.replace(/(^\s*)|(\s*$)/g, ""); 16 } 17 /** 18 *字符串-去掉前空白字符 19 */ 20 String.prototype.ltrim = function(){ 21 return this.replace(/(^\s*)/g, ""); 22 } 23 /** 24 *字符串-去掉后空白字符 25 */ 26 String.prototype.rtrim = function(){ 27 return this.replace(/(\s*$)/g, ""); 28 } 29 /** 30 *字符串-获取以ASCII编码字节数 英文占1字节 中文占2字节 31 */ 32 String.prototype.lenASCII=function(){ 33 return this.replace(/[^\x00-\xff]/g,'xx').length;//将所有非\x00-\xff字符换为xx两个字符,再计算字符串 34 } 35 /** 36 *字符串-获取以UNICODE编码字节数 一个字符均占2个字节 37 */ 38 String.prototype.lenUNICODE=function(){ 39 return this.length*2; 40 }
ps:若对js提供类型对象或自定义对象进行方法扩展,应利用原型prototype这个对象属性进行扩展,具体方式以下:
1 String.prototype.trim=function(){ 2 //...代码略 3 }; 4 String.prototype.ltrim=function(){ 5 //...代码略 6 };