JS常用方法--String.prototype使用!
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html><head> <title>New Document </title> <meta name="Generator" content="EditPlus"> <meta name="Author" content=""> <meta name="Keywords" content=""> <meta name="Description" content=""> <script language="javascript"> String.prototype.Replace = function(oldValue,newValue) { var reg = new RegExp(oldValue,"g"); return this.replace(reg, newValue); } //字符串替换;曾经很头疼写了很多代码,还是这个简单 function replace(obj) { alert(obj.value.Replace("a","d")); } // 另存为文件 function SaveCode(obj, filename) { var win = window.open('', '_blank', 'top=100'); var code = obj.innerText; code = code == null || code == "" ? obj.value : code; win.opener = null; win.document.write(code); win.document.execCommand('saveas', true, filename); win.close(); } // 问候 window.onload = function() { var now = new Date(); var hour = now.getHours(); var greeting; if (hour < 6) greeting = "凌晨好"; else if (hour < 10) greeting = "早上好"; else if (hour < 14) greeting = "中午好"; else if (hour < 18) greeting = "下午好"; else greeting = "晚上好"; document.getElementById("hi").innerHTML = "<font color=red>" + greeting + "</font>" ; } // 将光标停在对象的最后 function PutCursorAtLast(obj) { obj.focus(); var range = obj.createTextRange(); range.moveStart('character',obj.value.length); range.collapse(true); range.select(); } // 将光标停在对象的最前 function PutCursorAtFirst(obj) { obj.focus(); var range = obj.createTextRange(); range.moveStart('character',0); range.collapse(true); range.select(); } </script> </head><body><span id="hi"></span><br /> <span>curssor at last </span><br /> <input type="text" value="curssor at last" onclick="PutCursorAtLast(this)"> <br /> <span>curssor at first </span><br /> <input type="text" value="curssor at first" onclick="PutCursorAtFirst(this)"> <br /> <span>String.Replace </span><br /> <input type="TEXT" value="replace" onclick="replace(this)"> <br /> <span>save file </span><br /> <input type="text" value="hello word" onclick='SaveCode(this,"save")' /> </body></html>
// 返回字符的长度,一个中文算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行
<script type="text/javascript"> //by Go_Rush(阿舜) from http://ashun.cnblogs.com/ function $A(arrayLike){ for(var i=0,ret=[];i<arrayLike.length;i++) ret.push(arrayLike[i]) return ret }; Array.prototype.any=function(f){ for(var i=0;i<this.length;i++) if (f(this[i],i,this)) return true; return false }; //判断 字符串 是否符合 yyyy-mm-dd hh:mm:ss的日期格式, 格式正确而且闰年闰月等也要正确 String.prototype.isDateTime=function(){ try{ var arr=(this.length==19)?this.split(/\D/):[] --arr[1] eval("var d=new Date("+arr.join(",")+")") return Number(arr[0])==d.getFullYear() && Number(arr[1])==d.getMonth() && Number(arr[2])==d.getDate() && Number(arr[3])==d.getHours() && Number(arr[4])==d.getMinutes() && Number(arr[5])==d.getSeconds() }catch(x){return false} } /* alert("2002-12-12 10:10:40".isDateTime()) //true alert("2002-02-31 10:10:40".isDateTime()) //false alert("2002-22-31 10:10:40".isDateTime()) //false alert("2002-22-31 30:10:40".isDateTime()) //false */ // 检查 是否以特定的字符串结束 String.prototype.startsWith=function(){ var _string=this return $A(arguments).any(function(value){return _string.slice(0,value.length)==value}) }; /* alert("http://www.google.com/".startsWith("http://","ftp://","telnet://")) //true 满足其中任何一个就返回 true alert("http://www.google.com/".startsWith("https://","file://")) //false alert("abc".startsWith("a")) //true */ // 检查 是否以特定的字符串结束 String.prototype.endsWith=function(){ var _string=this return $A(arguments).any(function(value){return _string.slice(value.length*(-1))==value}) }; //从左边截取n个字符 ,如果包含汉字,则汉字按两个字符计算 String.prototype.left=function(n){ return this.slice(0,n-this.slice(0,n).replace(/[\x00-\xff]/g,"").length) }; /* alert("abcdefg".left(3)==="abc") alert("中国人cdefg".left(5)==="中国") alert("中国abcdefg".left(5)==="中国a") */ //从右边截取n个字符 ,如果包含汉字,则汉字按两个字符计算 String.prototype.right=function(n){ return this.slice(this.slice(-n).replace(/[\x00-\xff]/g,"").length-n) }; /* alert("abcdefg".right(3)==="efg") alert("cdefg中国人".right(5)==="国人") alert("abcdefg中国".right(5)==="g中国") */ </script>