首页 > 语言 > JavaScript > 正文

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 ;
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选