日期:2014-05-16  浏览次数:20316 次

使用prototype扩展JS内部对象String的功能

转自:http://j2ee.blog.sohu.com/18037298.html

?

(^\s+)|(\s+$)/g?
/ pattern /g?
是js正则字符串的语法?

g (全文查找出现的所有 pattern)?
i (忽略大小写)?
m (多行查找)

?我们知道在使用JS开发的时候,遇到很多的程序代码都要自己写。比如一字符串是否以某个字符串开头,是否和某个字符结尾等等这些都需要自己手动写一个函数来判断,而且JS内部对象String都没有提供类似的方法。为了节约宝贵的开发时间,把精力都不要浪费在这些个琐碎的事上,需要把整理一个JS函数库来做这些事情。当然了,写函数需要传递多余的参数,比如上面说到的,判断字符串是否以某个字符串开头,如果写函数,那么至少要传递两个参数过去。但是,现在我们可以用prototype原型方法来为所有的字符串都加上相应的方法,这样就可以直接调用了。比如我写的一个对JS内部对象String功能进行扩展的js代码如下:

<!--
/**
?*@Title:扩展JS内部对象的功能方法!使用prototype原型方法
?*@Author:铁木箱子
?*@Date:2006-10-17
?*/

/**
?*Desc:扩展String对象的方法!注意所有的方法都是返回新字符串,不会修改原字符串!
?*/
?
//在字符串末尾追加字符串
String.prototype.append=function(aStr){
?return this.concat(aStr);
}
?
//删除指定索引位置的字符,索引无效将不删除任何字符
String.prototype.deleteCharAt=function(sIndex){
?if(sIndex<0 || sIndex>=this.length){
??return this.valueOf();
?}else if(sIndex==0){
??return this.substring(1,this.length);
?}else if(sIndex==this.length-1){
??return this.substring(0,this.length-1);
?}else{
??return this.substring(0,sIndex)+this.substring(sIndex+1);
?}
}
?
//删除指定索引间的字符串.sIndex和eIndex所在的字符不被删除!
String.prototype.deleteString=function(sIndex,eIndex){
?if(sIndex==eIndex){
??return this.deleteCharAt(sIndex);
?}else{
??if(sIndex>eIndex){
???var tIndex=eIndex;
???eIndex=sIndex;
???sIndex=tIndex;
??}
??if(sIndex<0)sIndex=0;
??if(eIndex>this.length-1)eIndex=this.length-1;
??return this.substring(0,sIndex+1)+this.substring(eIndex,this.length);
?}
}
?
//检查字符串是否以某个字符串(aStr)结尾
String.prototype.endsWith=function(aStr){
?if(aStr.length>this.length)return false;
?return (this.lastIndexOf(aStr)==(this.length-aStr.length))?true:false;
}
?
//比较两个字符串是否相等。其实也可以直接使用==进行比较
String.prototype.equals=function(aStr){
?if(this.length!=aStr.length){
??return false;
?}else{
??for(var i=0;i<this.length;i++){
???if(this.charAt(i)!=aStr.charAt(i)){