js中String的常用擴(kuò)展,包括trim,檢查中文,url,emal,電話號(hào)碼,轉(zhuǎn)類型,格式化代碼等
//去掉字符串空間調(diào)用方式 字符串.trim()
String.prototype.trim = function()...{ return this.replace(/(^\s*)|(\s*$)/g, "");}
//求字符穿真實(shí)長(zhǎng)度漢字2個(gè)字節(jié) 字符串.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);}
//檢查電話號(hào)碼
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);}
//檢查整數(shù)
String.prototype.isNumber=function()...{return /^[0-9]+$/.test(this);}
// 整數(shù)轉(zhuǎn)換
String.prototype.toNumber = function(def)...{return isNaN(parseInt(this, 10)) ? def : parseInt(this, 10);}
// 小數(shù)轉(zhuǎn)換
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]];
});
};
聯(lián)系客服