常用的String原型

雪沫一隅發表於2018-12-20

對於常用的字串原型的舉例

 在字串末尾追加字串 
String.prototype.append = function (str) {
return this.concat(str);
}

 刪除指定索引位置的字元,索引無效將不刪除任何字元 
String.prototype.deleteCharAt = function (index) {
if (index < 0 || index >= this.length) {
return this.valueOf();
}
else if (index == 0) {
return this.substring(1, this.length);
}
else if (index == this.length – 1) {
return this.substring(0, this.length – 1);
}
else {
return this.substring(0, index) + this.substring(index + 1);
}
}
 刪除指定索引區間的字串 
String.prototype.deleteString = function (start, end) {
if (start == end) {
return this.deleteCharAt(start);
}
else {
if (start > end) {
var temp = start;
start = end;
end = temp;
}
if (start < 0) {
start = 0;
}
if (end > this.length – 1) {
end = this.length – 1;
}
return this.substring(0, start) + this.substring(end +1 , this.length);
}
}
 檢查字串是否以subStr結尾 
String.prototype.endWith = function (subStr) {
if (subStr.length > this.length) {
return false;
}
else {
return (this.lastIndexOf(subStr) == (this.length – subStr.length)) ? true : false;
}
}
 比較兩個字串是否相等,也可以直接用 == 進行比較 
String.prototype.equal = function (str) {
if (this.length != str.length) {
return false;
}
else {
for (var i = 0; i < this.length; i++) {
if (this.charAt(i) != str.charAt(i)) {
return false;
}
}
return true;
}
}
 比較兩個字串是否相等,不區分大小寫 
String.prototype.equalIgnoreCase = function (str) {
var temp1 = this.toLowerCase();
var temp2 = str.toLowerCase();
return temp1.equal(temp2);
}
 將指定的字串插入到指定的位置後面,索引無效將直接追加到字串的末尾 
String.prototype.insert = function (ofset, subStr) {
if (ofset < 0 || ofset >= this.length – 1) {
return this.append(subStr);
}
return this.substring(0, ofset + 1) + subStr + this.substring(ofset + 1);
}
 判斷字串是否數字串 
String.prototype.isAllNumber = function () {
for (var i = 0; i < this.length; i++) {
if (this.charAt(i) < `0` || this.charAt(i) > `9`) {
return false;
}
}
return true;
}
 將字串反序排列 
String.prototype.reserve = function () {
var temp = “”;
for (var i = this.length – 1; i >= 0; i–) {
temp = temp.concat(this.charAt(i));
}
return temp;
}
 將指定的位置的字元設定為另外指定的字元或字串.索引無效將直接返回不做任何處理 
String.prototype.setCharAt = function (index, subStr) {
if (index < 0 || index > this.length – 1) {
return this.valueOf();
}
return this.substring(0, index) + subStr + this.substring(index+1);
}
 檢查字串是否以subStr開頭 
String.prototype.startWith = function (subStr) {
if (subStr.length > this.length) {
return false;
}
return (this.indexOf(subStr) == 0) ? true : false;
}
 計算長度,每個漢字佔兩個長度,英文字元每個佔一個長度 
String.prototype.charLength = function () {
var temp = 0;
for (var i = 0; i < this.length; i++) {
if (this.charCodeAt(i) > 255) {
temp += 2;
}
else {
temp += 1;
}
}
return temp;
}
String.prototype.charLengthReg = function () {
return this.replace(/[^x00-xff]/g, “**”).length;
}
 去掉首尾空格 
String.prototype.trim = function () {
return this.replace(/(^s*)|(s*$)/g, “”);
}
 測試是否是數字 
String.prototype.isNumeric = function () {
var tmpFloat = parseFloat(this);
if (isNaN(tmpFloat))
return false;
var tmpLen = this.length – tmpFloat.toString().length;
return tmpFloat + “0”.Repeat(tmpLen) == this;
}
 測試是否是整數 
String.prototype.isInt = function () {
if (this == “NaN”)
return false;
return this == parseInt(this).toString();
}
 獲取N個相同的字串 
String.prototype.Repeat = function (num) {
var tmpArr = [];
for (var i = 0; i < num; i++) tmpArr.push(this);
return tmpArr.join(“”);
}
 除去左邊空白  
String.prototype.LTrim = function () {
return this.replace(/^s+/g, “”);
}
 除去右邊空白 
String.prototype.RTrim = function () {
return this.replace(/s+$/g, “”);
}
 除去兩邊空白  
String.prototype.trim = function () {
return this.replace(/(^s+)|(s+$)/g, “”);
}
 保留數字 
String.prototype.getNum = function () {
return this.replace(/[^d]/g, “”);
}
 保留字母 
String.prototype.getEn = function () {
return this.replace(/[^A-Za-z]/g, “”);
}
 保留中文
String.prototype.getCn = function () {
return this.replace(/[^u4e00-u9fa5uf900-ufa2d]/g, “”);
}
 得到位元組長度 
String.prototype.getRealLength = function () {
return this.replace(/[^x00-xff]/g, “–“).length;
}
 從左擷取指定長度的字串 
String.prototype.left = function (n) {
return this.slice(0, n);
}
 從右擷取指定長度的字串  
String.prototype.right = function (n) {
return this.slice(this.length – n);
}
 刪除首尾空格  
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);
}

系統中JS的擴充套件函式 

/清除兩邊的空格
String.prototype.trim = function() {
return this.replace(/(^s*)|(s*$)/g, “);
};
 合併多個空白為一個空白
String.prototype.ResetBlank = function() {
var regEx = /s+/g;
return this.replace(regEx, ` `);
};

保留數字
String.prototype.GetNum = function() {
var regEx = /[^d]/g;
return this.replace(regEx, “);
};

保留中文
String.prototype.GetCN = function() {
var regEx = /[^u4e00-u9fa5uf900-ufa2d]/g;
return this.replace(regEx, “);
};

String轉化為Number
String.prototype.ToInt = function() {
return isNaN(parseInt(this)) ? this.toString() : parseInt(this);
};

 得到位元組長度
String.prototype.GetLen = function() {
var regEx = /^[u4e00-u9fa5uf900-ufa2d]+$/;
if (regEx.test(this)) {
return this.length * 2;
} else {
var oMatches = this.match(/[x00-xff]/g);
var oLength = this.length * 2 – oMatches.length;
return oLength;
}
};

 獲取檔案全名
String.prototype.GetFileName = function() {
var regEx = /^.*/([^/?]*).*$/;
return this.replace(regEx, `$1`);
};

 數字補零
Number.prototype.LenWithZero = function(oCount) {
var strText = this.toString();
while (strText.length < oCount) {
strText = `0` + strText;
}
return strText;
};

Unicode還原
Number.prototype.ChrW = function() {
return String.fromCharCode(this);
};

 數字陣列由小到大排序
Array.prototype.Min2Max = function() {
var oValue;
for (var i = 0; i < this.length; i++) {
for (var j = 0; j <= i; j++) {
if (this[i] < this[j]) {
oValue = this[i];
this[i] = this[j];
this[j] = oValue;
}
}
}
return this;
};

 數字陣列由大到小排序
Array.prototype.Max2Min = function() {
var oValue;
for (var i = 0; i < this.length; i++) {
for (var j = 0; j <= i; j++) {
if (this[i] > this[j]) {
oValue = this[i];
this[i] = this[j];
this[j] = oValue;
}
}
}
return this;
};

 獲得數字陣列中最大項
Array.prototype.GetMax = function() {
var oValue = 0;
for (var i = 0; i < this.length; i++) {
if (this[i] > oValue) {
oValue = this[i];
}
}
return oValue;
};

 獲得數字陣列中最小項
Array.prototype.GetMin = function() {
var oValue = 0;
for (var i = 0; i < this.length; i++) {
if (this[i] < oValue) {
oValue = this[i];
}
}
return oValue;
};

 獲取當前時間的中文形式
Date.prototype.GetCNDate = function() {
var oDateText = “;
oDateText += this.getFullYear().LenWithZero(4) + new Number(24180).ChrW();
oDateText += this.getMonth().LenWithZero(2) + new Number(26376).ChrW();
oDateText += this.getDate().LenWithZero(2) + new Number(26085).ChrW();
oDateText += this.getHours().LenWithZero(2) + new Number(26102).ChrW();
oDateText += this.getMinutes().LenWithZero(2) + new Number(20998).ChrW();
oDateText += this.getSeconds().LenWithZero(2) + new Number(31186).ChrW();
oDateText += new Number(32).ChrW() + new Number(32).ChrW() + new Number(26143).ChrW() + new Number(26399).ChrW() + new String(`26085199682010819977222352011620845`).substr(this.getDay() * 5, 5).ToInt().ChrW();
return oDateText;
};
擴充套件Date格式化
Date.prototype.Format = function(format) {
var o = {
“M+”: this.getMonth() + 1, //月份
“d+”: this.getDate(), //日
“h+”: this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小時
“H+”: this.getHours(), //小時
“m+”: this.getMinutes(), //分
“s+”: this.getSeconds(), //秒
“q+”: Math.floor((this.getMonth() + 3) / 3), //季度
“S”: this.getMilliseconds() //毫秒
};
var week = {
“0”: “u65e5”,
“1”: “u4e00”,
“2”: “u4e8c”,
“3”: “u4e09”,
“4”: “u56db”,
“5”: “u4e94”,
“6”: “u516d”
};
if (/(y+)/.test(format)) {
format = format.replace(RegExp.$1, (this.getFullYear() + “”).substr(4 – RegExp.$1.length));
}
if (/(E+)/.test(format)) {
format = format.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? “u661fu671f” : “u5468”) : “”) + week[this.getDay() + “”]);
}
for (var k in o) {
if (new RegExp(“(” + k + “)”).test(format)) {
format = format.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : ((“00” + o[k]).substr((“” + o[k]).length)));
}
}
return format;
}
Date.prototype.Diff = function(interval, objDate) {
 若引數不足或 objDate 不是日期型別則回傳 undefined
if (arguments.length < 2 || objDate.constructor != Date) { return undefined; }
switch (interval) {
//計算秒差
case `s`: return parseInt((objDate – this) / 1000);
//計算分差
case `n`: return parseInt((objDate – this) / 60000);
//計算時差
case `h`: return parseInt((objDate – this) / 3600000);
//計算日差
case `d`: return parseInt((objDate – this) / 86400000);
//計算周差
case `w`: return parseInt((objDate – this) / (86400000 * 7));
//計算月差
case `m`: return (objDate.getMonth() + 1) + ((objDate.getFullYear() – this.getFullYear()) * 12) – (this.getMonth() + 1);
//計算年差
case `y`: return objDate.getFullYear() – this.getFullYear();
//輸入有誤
default: return undefined;
}
};

 檢測是否為空
Object.prototype.IsNullOrEmpty = function() {
var obj = this;
var flag = false;
if (obj == null || obj == undefined || typeof (obj) == `undefined` || obj == “) {
flag = true;
} else if (typeof (obj) == `string`) {
obj = obj.trim();
if (obj == “) {//為空
flag = true;
} else {//不為空
obj = obj.toUpperCase();
if (obj == `NULL` || obj == `UNDEFINED` || obj == `{}`) {
flag = true;
}
}
}
else {
flag = false;
}
return flag;
};

相關文章