js中String的常用扩展
js中String的常用扩展,包括trim,检查中文,url,emal,电话号码,转类型,格式化代码等
//去掉字符串空间调用方式 字符串.trim() String.prototype.trim = function(){ return this.replace(/(^\s*)|(\s*$)/g, "");} //求字符穿真实长度汉字2个字节 字符串.lengthw() String.prototype.lengthW = function(){ return this.replace(/[^\x00-\xff]/g,"**").length;} //判断是否email String.prototype.isEmail = function(){ return /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(this);} // 字符串中是否包含中文 String.prototype.existChinese = function(){return /^[\x00-\xff]*$/.test(this);} //检查url String.prototype.isUrl = function(){ return /^http[s]?:\/\/([\w-]+\.)+[\w-]+([\w-./?%&=]*)?$/i.test(this);} //检查电话号码 String.prototype.isPhoneCall = function(){ return /(^[0-9]{3,4}\-[0-9]{3,8}$)|(^[0-9]{3,8}$)|(^\([0-9]{3,4}\)[0-9]{3,8}$)|(^0{0,1}13[0-9]{9}$)/.test(this);} //检查整数 String.prototype.isNumber=function(){return /^[0-9]+$/.test(this);} // 整数转换 String.prototype.toNumber = function(def){return isNaN(parseInt(this, 10)) ? def : parseInt(this, 10);} // 小数转换 String.prototype.toMoney = function(def){return isNaN(parseFloat(this)) ? def : parseFloat(this);} //格式化代码 String.prototype.format = function() { var args = arguments; return this.replace(/{(\d{1})}/g, function() { return args[arguments[1]]; }); };