java.lang.String是Java中最重要的數據類型之一,它是由許多字符String API函數組成,但的有時候還是不夠,可以通過擴展來實現,下面就讓錯新技術頻道小編帶你進入下文了解擴展String功能的方法。
/***?刪除首尾空格?***/
String.prototype.Trim?=?function()?{
??return?this.replace(/(^/s*)|(/s*$)/g,?"");
}
/***?統計指定字符出現的次數?***/
String.prototype.Occurs?=?function(ch)?{
//??var?re?=?eval("/[^"+ch+"]/g");
//??return?this.replace(re,?"").length;
??return?this.split(ch).length-1;
}
/***?檢查是否由數字組成?***/
String.prototype.isDigit?=?function()?{
??var?s?=?this.Trim();
??return?(s.replace(//d/g,?"").length?==?0);
}
/***?檢查是否由數字字母和下劃線組成?***/
String.prototype.isAlpha?=?function()?{
??return?(this.replace(//w/g,?"").length?==?0);
}
/***?檢查是否為數?***/
String.prototype.isNumber?=?function()?{
??var?s?=?this.Trim();
??return?(s.search(/^[+-]?[0-9.]*$/)?>=?0);
}
/***?返回字節數?***/
String.prototype.lenb?=?function()?{
??return?this.replace(/[^/x00-/xff]/g,"**").length;
}
/***?檢查是否包含漢字?***/
String.prototype.isInChinese?=?function()?{
??return?(this.length?!=?this.replace(/[^/x00-/xff]/g,"**").length);
}
/***?簡單的email檢查?***/
String.prototype.isEmail?=?function()?{
var?strr;
??var?mail?=?this;
var?re?=?/(/w+@/w+/./w+)(/.{0,1}/w*)(/.{0,1}/w*)/i;
re.exec(mail);
if(RegExp.$3!=""?&&?RegExp.$3!="."?&&?RegExp.$2!=".")
????strr?=?RegExp.$1+RegExp.$2+RegExp.$3;
else
if(RegExp.$2!=""?&&?RegExp.$2!=".")
??????strr?=?RegExp.$1+RegExp.$2;
else
???? strr?=?RegExp.$1;
return?(strr==mail);
}
/***?簡單的日期檢查,成功返回日期對象?***/
String.prototype.isDate?=?function()?{
??var?p;
??var?re1?=?/(/d{4})[年./-](/d{1,2})[月./-](/d{1,2})[日]?$/;
??var?re2?=?/(/d{1,2})[月./-](/d{1,2})[日./-](/d{2})[年]?$/;
??var?re3?=?/(/d{1,2})[月./-](/d{1,2})[日./-](/d{4})[年]?$/;
??if(re1.test(this))?{
????p?=?re1.exec(this);
????return?new?Date(p[1],p[2],p[3]);
??}
??if(re2.test(this))?{
????p?=?re2.exec(this);
????return?new?Date(p[3],p[1],p[2]);
??}
??if(re3.test(this))?{
????p?=?re3.exec(this);
????return?new?Date(p[3],p[1],p[2]);
??}
??return?false;
}
/***?檢查是否有列表中的字符字符?***/
String.prototype.isInList?=?function(list)?{
??var?re?=?eval("/["+list+"]/");
??return?re.test(this);
}
上文是關于擴展String功能的方法,相信大家都有了一定的了解,想要了解更多的技術信息,請繼續關注錯新技術頻道吧!
新聞熱點
疑難解答
圖片精選