js 常用方法


String.prototype 使用

以下为web开发中常用到的js方法;收集并整理出来;简单的就不写出来了

 1 <! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
 2 < HTML >
 3 < HEAD >
 4 < TITLE > New Document  </ TITLE >
 5 < META  NAME ="Generator"  CONTENT ="EditPlus" >
 6 < META  NAME ="Author"  CONTENT ="" >
 7 < META  NAME ="Keywords"  CONTENT ="" >
 8 < META  NAME ="Description"  CONTENT ="" >
 9 < script  language =javascript >
10    String.prototype.Replace = function(oldValue,newValue) 
11    
12        var reg = new RegExp(oldValue,"g"); 
13        return this.replace(reg, newValue); 
14    }

15    //字符串替换;曾经很头疼写了很多代码,还是这个简单
16    function replace(obj)
17    {
18        alert(obj.value.Replace("a","d"));
19    }

20
21    // 另存为文件
22    function SaveCode(obj, filename) 
23    {
24        var win = window.open('', '_blank', 'top=100'); 
25        var code = obj.innerText; 
26        code = code == null || code == "" ? obj.value : code; 
27        win.opener = null;
28        win.document.write(code);
29        win.document.execCommand('saveas', true, filename);
30        win.close();
31    }

32    // 问候
33    window.onload = function()
34    {    
35        var now = new Date();
36        var hour = now.getHours();
37        var greeting;
38        if (hour < 6)
39            greeting = "凌晨好";
40        else if (hour < 10)
41            greeting = "早上好";
42        else if (hour < 14)
43            greeting = "中午好";
44        else if (hour < 18)
45            greeting = "下午好";
46        else 
47            greeting = "晚上好";
48            
49        document.getElementById("hi").innerHTML = "<font color=red>" + greeting + "</font>" ;
50    }

51    // 将光标停在对象的最后
52    function PutCursorAtLast(obj) 
53    {  
54        obj.focus();
55        var range = obj.createTextRange(); 
56        range.moveStart('character',obj.value.length); 
57        range.collapse(true); 
58        range.select(); 
59    }

60    // 将光标停在对象的最前
61    function PutCursorAtFirst(obj) 
62    {  
63        obj.focus();
64        var range = obj.createTextRange(); 
65        range.moveStart('character',0); 
66        range.collapse(true); 
67        range.select(); 
68    }

69
</ script >
70 </ HEAD >
71
72 < BODY >
73      < span  id ="hi" ></ span >
74      < br />
75      < span > curssor at last  </ span >
76      < br />
77      < input  type =text  value ="curssor at last"  onclick =PutCursorAtLast(this) >
78      < br />
79      < span > curssor at first  </ span >
80      < br />
81      < input  type =text  value ="curssor at first"  onclick =PutCursorAtFirst(this) >
82      < br />
83      < span > String.Replace  </ span >
84      < br />
85      < INPUT  TYPE =TEXT  value ="replace"  ONCLICK =replace(this) >
86      < br />
87      < span > save file  </ span >
88      < br />
89      < input  type =text  value ="hello word"  onclick =SaveCode(this,"save") >
90 </ BODY >
91 </ HTML >
92


//  返回字符的长度,一个中文算2个
String.prototype.ChineseLength= function()

    return this.replace(/[^\x00-\xff]/g,"**").length;
}

//  判断字符串是否以指定的字符串结束
String.prototype.EndsWith =  function(str) 
{
    return this.substr(this.length - str.length) == str;
}

//  去掉字符左端的的空白字符
String.prototype.LeftTrim =  function()
{
    return this.replace(/(^[\\s]*)/g, "");
}

//  去掉字符右端的空白字符
String.prototype.RightTrim =  function()
{
    return this.replace(/([\\s]*$)/g, "");
}

//  判断字符串是否以指定的字符串开始
String.prototype.StartsWith =  function(str) 
{
    return this.substr(0, str.length) == str;
}

//  去掉字符两端的空白字符
String.prototype.Trim =  function()
{
    return this.replace(/(^\s*)|(\s*$)/g, "");
}

都是基于 String.prototype 的扩展:

 起因是有个网友和我讨论两个函数,

一个是 isDateTime (判断字符是否是符合 yyyy-mm-dd hh:mm:ss日期格式)
另一个是 left 函数,类似vbscript的left 实现中英文字符的混合截取。

他两个函数都用了循环,还用了N多 if 语句,每个函数都超过了40行代码,问我有无好的办法精简一下。
于是,我就写出了下面的代码,不敢说最效率最高,但是已经是够精简了, left函数才1行
 1 <script type="text/javascript">
 2 
 3 //by Go_Rush(阿舜) from http://ashun.cnblogs.com/
 4 
 5 function $A(arrayLike){
 6     for(var i=0,ret=[];i<arrayLike.length;i++) ret.push(arrayLike[i])
 7     return ret
 8 };
 9 Array.prototype.any=function(f){
10     for(var i=0;i<this.length;i++) if (f(this[i],i,this)) return true;
11     return false
12 };
13 
14 
15 
16 //判断 字符串 是否符合 yyyy-mm-dd hh:mm:ss的日期格式, 格式正确而且闰年闰月等也要正确
17 
18 String.prototype.isDateTime=function(){  
19     try{
20         var arr=(this.length==19)?this.split(/\D/):[]
21         --arr[1]
22         eval("var d=new Date("+arr.join(",")+")")    
23         return     Number(arr[0])==d.getFullYear() && Number(arr[1])==d.getMonth() 
24                      && Number(arr[2])==d.getDate() && Number(arr[3])==d.getHours()
25                     && Number(arr[4])==d.getMinutes() && Number(arr[5])==d.getSeconds()
26     }catch(x){return false}
27 }
28 
29 /*
30 alert("2002-12-12 10:10:40".isDateTime())  //true
31 alert("2002-02-31 10:10:40".isDateTime())  //false
32 alert("2002-22-31 10:10:40".isDateTime())  //false
33 alert("2002-22-31 30:10:40".isDateTime())  //false
34 */
35 
36 
37 // 检查 是否以特定的字符串结束
38 String.prototype.startsWith=function(){
39     var _string=this
40     return $A(arguments).any(function(value){return _string.slice(0,value.length)==value})
41 };
42 /*
43 alert("http://www.google.com/".startsWith("http://","ftp://","telnet://"))  //true  满足其中任何一个就返回 true
44 alert("http://www.google.com/".startsWith("https://","file://"))  //false
45 alert("abc".startsWith("a"))  //true
46 */
47 
48 
49 // 检查 是否以特定的字符串结束
50 String.prototype.endsWith=function(){
51     var _string=this
52     return $A(arguments).any(function(value){return _string.slice(value.length*(-1))==value})
53 };
54 
55 
56 
57 //从左边截取n个字符 ,如果包含汉字,则汉字按两个字符计算
58 String.prototype.left=function(n){
59     return this.slice(0,n-this.slice(0,n).replace(/[\x00-\xff]/g,"").length)
60 };
61 /*
62 alert("abcdefg".left(3)==="abc")
63 alert("中国人cdefg".left(5)==="中国")
64 alert("中国abcdefg".left(5)==="中国a")
65 */
66 
67 
68 
69 
70 //从右边截取n个字符 ,如果包含汉字,则汉字按两个字符计算
71 String.prototype.right=function(n){
72     return this.slice(this.slice(-n).replace(/[\x00-\xff]/g,"").length-n)
73 };
74 
75 /*
76 alert("abcdefg".right(3)==="efg")
77 alert("cdefg中国人".right(5)==="国人")
78 alert("abcdefg中国".right(5)==="g中国")
79 */
80 
81 </script>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值