收集一些常用的正则表达式(匹配中文字符、匹配双字节字符、匹配HTML标记、匹配空行 and so on~~~)
/**
* 计算字符串长度,将非宽字符计算为半个字符
*
* @param str
* @returns
*/
function gbLength(str) {
return typeof str === "string" ? str.length + str.replace(/[x00-x7f]/g, '').length + 1 >> 1 : 0;
}
/**
* 获取字符串的指定长度的子串,将非宽字符计算为半个字符
*
* @param str
* @param length
* @returns
*/
function gbSubstr(str, length) {
if (typeof str !== "string")
return str;
length += length;
for ( var n = 0, L = str.length; n < L && length > 0; n++){
length -= str.charCodeAt(n) > 127 ? 2 : 1;
}
return str.substr(0, n);
}
/**
* 切割指定字符串的指定长度子串,如果长度超过指定长度,则丢弃末尾两个字符并附加...
*
* @param str
* @param len
* @returns
*/
function fit_length(str, len){
len = len || 16;
if (typeof str !== "string" || str.length <= len || gbLength(str) <= len){
return str;
}
var ret = gbSubstr(str, len - 2);
return ret + '..';
}
var replaceCJK = /[^x00-xff]/g,
testCJK = /[^x00-xff]/;
cjkLength: function(strValue){
return strValue.replace(replaceCJK, "lv").length;
},
isCjk: function(strValue){
return testCJK.test(strValue);
},
cutString: function(str,len,suffix,slen){
suffix = suffix || '';
slen = slen || suffix.length;
if(str.length > len){
str = str.substr(0,len - slen) + suffix;
}
return str;
},
cutCjkString: function(str,len,suffix,slen){
suffix = suffix || '';
slen = slen || suffix.length;
len -= slen;
if(this.cjkLength(str) <= len){
return str;
}
var s = str.split(''),c = 0,tmpA = [];
for(var i=0;i if(c < len){ tmpA[tmpA.length] = s[i]; } if(this.isCjk(s[i])){ c += 2; }else{ c += 1; } } return tmpA.join('') + suffix; } }