javascript 自定義常用方法第1/2頁
2024-05-06 14:14:19
供稿:網友
比如說頁面的字符處理,js的正則表達式驗證等等。下面我就將我自己淺薄的開發經驗綜合網上的龐雜資源稍稍綜合整理一下,省得自己以后要用到時再搜索了。這個系列我會將平時常用的函數歸納整理起來,全當作是拋磚引玉吧。
Code is cheap.看代碼:
一、常見的字符串處理函數
// 返回字符的長度,一個中文算2個
String.prototype.ChineseLength = function() {
return this .replace( / [ ^ /x00 - /xff] / g, " ** " ).length;
}
// 去掉字符串兩端的空白字符
String.prototype.Trim = function() {
return this .replace( / ( ^ /s + ) | (/s + $) / g, "" );
}
// 去掉字符左端的的空白字符
String.prototype.LeftTrim = function() {
return this .replace( / ( ^ [/s] * ) / g, "" );
}
// 去掉字符右端的空白字符
String.prototype.RightTrim = function() {
return this .replace( / ([/s] * $) / g, "" );
}
/* 忽略大小寫比較字符串是否相等
注:不忽略大小寫比較用 == 號 */
String.prototype.IgnoreCaseEquals = function(str) {
return this .toLowerCase() == str.toLowerCase();
}
/* 不忽略大小寫比較字符串是否相等 */
String.prototype.Equals = function(str) {
return ( this == str);
}
/* 比較字符串,根據結果返回 -1, 0
返回值 相同:0 不相同:-1
*/
String.prototype.CompareTo = function(str) {
if ( this == str) {
return 0 ;
} else
return - 1 ;
}
// 字符串替換
String.prototype.Replace = function(oldValue, newValue) {
var reg = new RegExp(oldValue, " g " );
return this .replace(reg, newValue);
}
// 檢查是否以特定的字符串結束
String.prototype.EndsWith = function(str) {
return this .substr( this .length - str.length) == str;
}
// 判斷字符串是否以指定的字符串開始
String.prototype.StartsWith = function(str) {
return this .substr( 0 , str.length) == str;
}
// 從左邊截取n個字符
String.prototype.LeftSlice = function(n) {
return this .substr( 0 , n);
}
// 從右邊截取n個字符
String.prototype.RightSlice = function(n) {
return this .substring( this .length - n);
}
// 統計指定字符出現的次數
String.prototype.Occurs = function(ch) {
// var re = eval("/[^"+ch+"]/g");
// return this.replace(re, "").length;
return this .split(ch).length - 1 ;
}
/* 構造特定樣式的字符串,用 <span></span> 包含 */
String.prototype.Style = function(style) {
return " <span style=/ "" .concat(style, " / " > " , this , " </span> " );
}
// 構造類似StringBuilder的函數(連接多個字符串時用到,很方便)
function StringBuilder(str) {
this .tempArr = new Array();
}
StringBuilder.prototype.Append = function(value) {
this .tempArr.push(value);
return this ;