String.prototype 几个简洁的字符处理函数 (转)
生活随笔
收集整理的這篇文章主要介紹了
String.prototype 几个简洁的字符处理函数 (转)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
都是基于 String.prototype 的擴(kuò)展:
?起因是有個網(wǎng)友和我討論兩個函數(shù),
一個是 isDateTime (判斷字符是否是符合 yyyy-mm-dd hh:mm:ss日期格式)
另一個是 left 函數(shù),類似vbscript的left 實(shí)現(xiàn)中英文字符的混合截取。
他兩個函數(shù)都用了循環(huán),還用了N多 if 語句,每個函數(shù)都超過了40行代碼,問我有無好的辦法精簡一下。
于是,我就寫出了下面的代碼,不敢說最效率最高,但是已經(jīng)是夠精簡了, left函數(shù)才1行
?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?//?檢查?是否以特定的字符串結(jié)束
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?//?檢查?是否以特定的字符串結(jié)束
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>
轉(zhuǎn)載于:https://www.cnblogs.com/RobotTech/archive/2006/12/29/607495.html
總結(jié)
以上是生活随笔為你收集整理的String.prototype 几个简洁的字符处理函数 (转)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【docker】常用docker命令,及
- 下一篇: zookeeper使用和原理探究