几个高效,简洁的字符处理函数

  都是基于 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>