JavaScript string 字符串类型的扩展函数

1. Js 判断前缀后缀代码和判空(含全部是空格):

<span style="font-size:14px;">// Js 判断后缀 
String.prototype.endsWith = function(suffix) {  
    return this.indexOf(suffix, this.length - suffix.length) !== -1;  
};  

// Js 判断前缀
if (typeof String.prototype.startsWith != 'function') {
  // see below for better implementation!
  String.prototype.startsWith = function (str){
    return this.indexOf(str) == 0;
  };
}  
  
// Js 判空(含全部是空格)
String.prototype.IsNullEmptyOrSpace = function()  
{   
   if (this== null) return true;  
      return this.replace(/s/g, '').length == 0;  
};

// 其他
String.prototype.trim = function()     

{     

    // 用正则表达式将前后空格     

    // 用空字符串替代。     

    var t = this.replace(/(^\s*)|(\s*$)/g, "");   

    return t.replace(/(^ *)|( *$)/g, "");   

} 

String.prototype.trim = function()   
{     
    //用来判断全角与半角空格   
    return this.replace(/(^[\s ]*)|([\s ]*$)/g,"");    
   // 用正则表达式将前后空格     
   // 用空字符串替代。     
   //return this.replace(/(^\s*)|(\s*$)/g, "");     
}</span>



2. 去前后空格

<span style="font-size:14px;">//去除左边的空格
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, "");
}</span>
3. 取子串

<span style="font-size:14px;">//得到左边的字符串
String.prototype.Left  function(len)
{
        if(isNaN(len)||lennull)
        {
                len  this.length;
        }
        else
        {
                if(parseInt(len)<0||parseInt(len)>this.length)
                {
                        len  this.length;
                }
        }
         
        return this.substr(0,len);
}
 
/*
//得到右边的字符串
*/
String.prototype.Right  function(len)
{
        if(isNaN(len)||lennull)
        {
                len  this.length;
        }
        else
        {
                if(parseInt(len)<0||parseInt(len)>this.length)
                {
                        len  this.length;
                }
        }
         
        return this.substring(this.length-len,this.length);
}
 
/*
//得到中间的字符串,注意从0开始
*/
String.prototype.Mid  function(start,len)
{
        return this.substr(start,len);
}
 
/*
//在字符串里查找另一字符串:位置从0开始
*/
String.prototype.InStr  function(str)
{
        if(strnull)
        {
                str  "";
        }
         
        return this.indexOf(str);
}
/*
//在字符串里反向查找另一字符串:位置0开始
*/
String.prototype.InStrRev  function(str)
{
        if(strnull)
        {
                str  "";
        }
         
        return this.lastIndexOf(str);
}
</span>

4. 验证常用格式

<span style="font-size:14px;">//是否是正确的IP地址
String.prototype.isIP  function()
{
        var reSpaceCheck  /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/;
        if (reSpaceCheck.test(this))
        {
                this.match(reSpaceCheck);
                if (RegExp.$1 < 255 && RegExp.$1 > 0 
                 && RegExp.$2 < 255 && RegExp.$2 > 0 
                 && RegExp.$3 < 255 && RegExp.$3 > 0 
                 && RegExp.$4 < 255 && RegExp.$4 > 0) 
                {
                        return true;     
                }
                else
                {
                        return false;
                }
        }
        else
        {
                return false;
        }
    
}
 
/*
//是否是正确的长日期
*/
String.prototype.isLongDate  function()
{
        var r  this.replace(/(^\s*)|(\s*$)/g, "").match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/); 
        if(rnull)
        {
                return false; 
        }
        var d  new Date(r[1], r[3]-1,r[4],r[5],r[6],r[7]); 
        return (d.getFullYear()r[1]&&(d.getMonth()+1)r[3]&&d.getDate()r[4]&&d.getHours()r[5]&&d.getMinutes()r[6]&&d.getSeconds()r[7]);
}
/*
//是否是正确的短日期
*/
String.prototype.isShortDate  function()
{
        var r  this.replace(/(^\s*)|(\s*$)/g, "").match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/); 
        if(rnull)
        {
                return false; 
        }
        var d  new Date(r[1], r[3]-1, r[4]); 
        return (d.getFullYear()r[1]&&(d.getMonth()+1)r[3]&&d.getDate()r[4]);
}
/*
//是否是正确的日期
*/
String.prototype.isDate  function()
{
        return this.isLongDate()||this.isShortDate();
}
/*
//是否是手机
*/
String.prototype.isMobile  function()
{
        return /^0{0,1}13[0-9]{9}$/.test(this);
}
/*
//是否是邮件
*/
String.prototype.isEmail  function()
{
        return /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(this);
}
/*
//是否是邮编(中国)
*/
String.prototype.isZipCode  function()
{
        return /^[\\d]{6}$/.test(this);
}
/*
//是否是有汉字
*/
String.prototype.existChinese  function()
{
        //[\u4E00-\u9FA5]為漢字﹐[\uFE30-\uFFA0]為全角符號
        return /^[\x00-\xff]*$/.test(this);
}
/*
//是否是合法的文件名/目录名
*/
String.prototype.isFileName  function()
{
        return !/[\\\/\*\?\|:"<>]/g.test(this);
}
/*
//是否是有效链接
*/
String.prototype.isUrl  function()
{
        return /^http[s]?:\/\/([\w-]+\.)+[\w-]+([\w-./?%&]*)?$/i.test(this);
}
 
/*
//是否是有效的身份证(中国)
*/
String.prototype.isIDCard  function()
{
        var iSum0;
        var info"";
        var sId  this;
        var aCity{11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"};
        if(!/^\d{17}(\d|x)$/i.test(sId))
        {
                return false;
        }
        sIdsId.replace(/x$/i,"a");
        //非法地区
        if(aCity[parseInt(sId.substr(0,2))]null)
        {
                return false;
        }
        var sBirthdaysId.substr(6,4)+"-"+Number(sId.substr(10,2))+"-"+Number(sId.substr(12,2));
        var dnew Date(sBirthday.replace(/-/g,"/"))
         
        //非法生日
        if(sBirthday!(d.getFullYear()+"-"+ (d.getMonth()+1) + "-" + d.getDate()))
        {
                return false;
        }
        for(var i  17;i>0;i--) 
        {
                iSum + (Math.pow(2,i) % 11) * parseInt(sId.charAt(17 - i),11);
        }
        if(iSum%11!1)
        {
                return false;
        }
        return true;
}
/*
//是否是有效的电话号码(中国)
*/
String.prototype.isPhoneCall  function()
{
        return /(^[0-9]{3,4}\-[0-9]{3,8}$)|(^[0-9]{3,8}$)|(^\([0-9]{3,4}\)[0-9]{3,8}$)|(^0{0,1}13[0-9]{9}$)/.test(this);
}
 
/*
//是否是数字
*/
String.prototype.isNumeric  function(flag)
{
        //验证是否是数字
        if(isNaN(this))
        {
                return false;
        }
        switch(flag)
        {
                case null:        //数字
                case "":
                        return true;
                case "+":        //正数
                        return                /(^\+?|^\d?)\d*\.?\d+$/.test(this);
                case "-":        //负数
                        return                /^-\d*\.?\d+$/.test(this);
                case "i":        //整数
                        return                /(^-?|^\+?|\d)\d+$/.test(this);
                case "+i":        //正整数
                        return                /(^\d+$)|(^\+?\d+$)/.test(this);                        
                case "-i":        //负整数
                        return                /^[-]\d+$/.test(this);
                case "f":        //浮点数
                        return                /(^-?|^\+?|^\d?)\d*\.\d+$/.test(this);
                case "+f":        //正浮点数
                        return                /(^\+?|^\d?)\d*\.\d+$/.test(this);                        
                case "-f":        //负浮点数
                        return                /^[-]\d*\.\d$/.test(this);                
                default:        //缺省
                        return true;                        
        }
}
/*
//是否是颜色(#FFFFFF形式)
*/
String.prototype.IsColor  function()
{
        var temp         this;
        if (temp"") return true;
        if (temp.length!7) return false;
        return (temp.search(/\#[a-fA-F0-9]{6}/) ! -1);
}

</span>

5. 格式转换(全角,日期,Html编码)

<span style="font-size:14px;"><span style="font-size:14px;">//转换成全角

String.prototype.toCase  function()
{
        var tmp  "";
        for(var i0;i<this.length;i++)
        {
                if(this.charCodeAt(i)>0&&this.charCodeAt(i)<255)
                {
                        tmp + String.fromCharCode(this.charCodeAt(i)+65248);
                }
                else
                {
                        tmp + String.fromCharCode(this.charCodeAt(i));
                }
        }
        return tmp
}
/*
//对字符串进行Html编码
*/
String.prototype.toHtmlEncode  function()
{
        var str  this;
        strstr.replace(/&/g,"&");
        strstr.replace(/</g,"<");
        strstr.replace(/>/g,">");
        strstr.replace(/\'/g,"'");
        strstr.replace(/\"/g,""");
        strstr.replace(/\n/g,"<br>");
        strstr.replace(/\ /g," ");
        strstr.replace(/\t/g,"    ");
        return str;
}
/*
//转换成日期
*/
String.prototype.toDate  function()
{
        try
        {
                return new Date(this.replace(/-/g, "\/"));
        }
        catch(e)
        {
                return null;
        }
}</span></span>


6.其他

<span style="font-size:14px;">//计算字符串打印长度
String.prototype.LengthW  function()
{
        return this.replace(/[^\x00-\xff]/g,"**").length;
}

// 替换字符串
String.prototype.replaceAll function(find, replace) {
  return this.replace(new RegExp(find, 'g'), replace);
}</span>

7.删除首尾空格

<span style="font-size:14px;">/**
 * -------------------------------------------------------------
 * 删除首尾空格
 * 如果限定了长度的话, 则区分全/半角截短字符串, 2个ASCII字符按1个字符计数
 * 截取后的显示长度不会超过限定长度, 省略号也计算在内
 * -------------------------------------------------------------
 * 如: " abc ".trim() --> "abc"
 * 如: "even偶数".trim(3) --> "<span title=\"even偶数\">even..</span>"
 * 如: "even偶数".trim(4) --> "even偶数" // 4个英文=2个汉字
 * 如: "even偶数!".trim(4) --> "<span title=\"even偶数!\">even偶..</span>"
 * 如: "odd奇数".trim(2) --> "<span title="odd奇数">od..</span>"
 * -------------------------------------------------------------
 * author: zhaohuihua
 * date: 2011-01-05
 * -------------------------------------------------------------
 */
String.prototype.trim = function(len) {
	var s = this.replace(/(^\s+|\s+$)/g, "");
	if(len === undefined || isNaN(len = parseInt(len)))
		return s;
	var idx = 0, charlen = 0; len = (len - 1) * 2;
	for(var i = 0; i < s.length; i ++) {
		var code = s.charCodeAt(i);
		var ascii = code >= 0 && code <= 255;
		if((charlen += (ascii ? 1 : 2)) <= len) idx ++;
	}
	if(charlen <= len + 2) return s;
	else return "<span title=\"{0}\">{1}..</span>".format(s, s.substring(0,idx));
};</span>

8.求字符串的长度, 1个汉字按2个字符计算

/**
 * 求字符串的长度, 1个汉字按2个字符计算
 */
String.prototype.size = function(len) {
	var count = 0;
	for(var i = 0; i < this.length; i ++) {
		var code = this.charCodeAt(i);
		count += (code >= 0 && code <= 255) ? 1 : 2;
	}
	return count;
};

9.字符串格式化

/**
 * -------------------------------------------------------------
 * 字符串格式化
 * -------------------------------------------------------------
 * 如: "Name:{0}, Email:{1}".format("zhaohuihua", "zhaohuihua@126.com")
 * --> Name:zhaohuihua, Email:zhaohuihua@126.com
 * -------------------------------------------------------------
 * author: zhaohuihua
 * date: 2011-01-05
 * -------------------------------------------------------------
 */
String.prototype.format = function() {
	var args = arguments;
	return this.replace(/\{(\d{1,2})\}/g, function(old, index) {
		var value = args[index]
		return value === undefined ? "" : value;
	});
};


10.字符串加载JSON数据, 是字符串格式化的加强版

/**
 * -------------------------------------------------------------
 * 字符串加载JSON数据, 是字符串格式化的加强版
 * -------------------------------------------------------------
示例:
var json = {
    id:1001, name:"Avril Lavigne", extra:{download:1888, click:1999},
    image:[{type:"pvw",path:"1001.1.jpg"},{type:"main",path:"1001.2.jpg"}],
    music:["Runaway", "Innocence", "Contagious"]
};
"<li>{id}</li><li>{name.substring(0, 5)}</li>".load(json)
--> <li>1001</li><li>Avril</li>
"<li>{extra.click}</li><li>{image[1].path}</li>".load(json)
--> <li>1999</li><li>1001.2.jpg</li>
"<li>{music[0]}</li><li>{music[1]}</li><li>{music[2]}</li>".load(json)
--> <li>Runaway</li><li>Innocence</li><li>Contagious</li>
 * -------------------------------------------------------------
 * author: zhaohuihua
 * date: 2011-01-05
 * -------------------------------------------------------------
 */
String.prototype.load = function(json) {
	// 首字母不能为数字, 以免与format()冲突
	var RPL = /\{([^0-9][^{}]*)\}/ig;
	return this.replace(RPL, function(old, exp) {
		try {
			var isArray = /\[[0-9]+\].*/.test(exp),
				value = eval("json" + (isArray ? "" : ".") + exp);
			return value === undefined ? "" : value;
		} catch (e) {
			return "";
		}
	});
};

11.相当于oracle的decode函数

/**
 * -------------------------------------------------------------
 * 相当于oracle的decode函数
 * -------------------------------------------------------------
 * 如: "1".decode("1", "男", "2", "女", "未知") --> 男
 * 如: "3".decode("1", "男", "2", "女", "未知") --> 未知
 * -------------------------------------------------------------
 * author: zhaohuihua
 * date: 2011-01-05
 * -------------------------------------------------------------
 */
String.prototype.decode = function() {
	if(arguments.length < 2) return null; // 参数不够
	for(var i = 0; i < arguments.length;) {
		// 每两个为一组
		var key = arguments[i++], val = arguments[i++];
		if(this == key) return val;
		// 最后多出来的一个为默认值
		if(i + 1 == arguments.length) return arguments[i];
	}
	return null;
};


其他:

String.prototype.include = function(t) { return this.indexOf(t) >= 0 ? true : false; };
String.prototype.trim = function(){ var r = /^\s+|\s+$/g;return this.replace(r,'');};
String.prototype.unescHtml = function(){ var i,e={'<':'<','>':'>','&':'&','"':'"'},t=this; for(i in e) t=t.replace(new RegExp(i,'g'),e[i]); return t;};
String.prototype.escHtml = function(){ var i,e={'&':'&','<':'<','>':'>','"':'"'},t=this; for(i in e) t=t.replace(new RegExp(i,'g'),e[i]); return t;};
String.prototype.escAttr = function(){var t = this; t = t.replace('"',""");return t;};
String.prototype.encodeURI = function(){var t = this;return encodeURIComponent(t);};
String.prototype.decodeURI = function(){var t = this;var t1 = decodeURIComponent(t); while(t != t1){t=t1;t1=decodeURIComponent(t);}return t;};
String.prototype.format = function(){var t=this;for(var i=0;i<arguments.length;i++){t = t.replace('{' + (i) + '}',arguments[i]);}return t;};
String.prototype.isEmail = function(){return /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(this);};
String.prototype.startWith = function(str){var t=this;return t.indexOf(str) == 0;};
String.prototype.endWith = function(str){var t = this;return t.substring(t.length-str.length,t.length) == str;};
String.prototype.isUrl = function(){var reg = /^http:\/\/[A-Za-z0-9\-]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/; 
var t = this; return reg.test(t);};
String.prototype.isNumber = function(){var reg = /^[\d]*[.]?\d*$/; 
var t = this; return reg.test(t);};
String.prototype.isEmpty = function(){
    var t = this.trim();
    var tem = t;
    var replaces = [' ','<br/>','<br>',' ',' ','\r','\n',/<p><\/p>/ig];
    while(true){
        for(var i=0;i<replaces.length;i++){
            tem = tem.replace(replaces[i],'');
        }
        tem = tem.trim();
        if(tem == t)break;
        else {t = tem;}
    }
    return tem == '';
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值