String对象的扩展函数:
String.prototype.trim = function() { return this.replace(/^/s+|/s+$/g,""); } String.prototype.ltrim = function() { return this.replace(/^/s+/g,""); } String.prototype.rtrim = function() { return this.replace(//s+$/g,""); } String.prototype.splitAndTrim = function($delimiter, $limit) { var $ss = this.split($delimiter, $limit); for(var $i=0; $i<$ss.length; $i++) $ss[$i] = $ss[$i].trim(); return $ss; } String.prototype.htmlEntities = function () { return this.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'); } String.prototype.stripTags = function () { return this.replace(/<([^>]+)>/g,''); } String.prototype.toArray = function() { return this.split(''); } String.prototype.toIntArray = function() { var returnArray = []; for (var i=0; i<this.length; i++) { returnArray.push(this.charCodeAt(i)); } return returnArray; } String.prototype.replaceAll = function($old, $snew){ return this.replace(new RegExp($old,"gm"),$snew); }
变量替换
var a = "I Love {0}, and You Love {1},Where are {0}!";a.format("You","Me"); String.prototype.format = function(){ var args = arguments; return this.replace(//{(/d+)/}/g,function(m,i,o,n){ return args[i]; }); }
在字符串末尾追加字符串
String.prototype.append = function($str){ return this.concat($str); }
删除指定索引位置的字符,索引无效将不删除任何字符
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所在的字符不被删除!依赖deleteCharAt
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); } }
检查字符串是否以某个字符串(str)结尾
String.prototype.endsWith = function($str){ return this.substr(this.length - $str.length) == $str; }
检查该字符串是否以某个字符串开始
String.prototype.startsWith = function(str){ return this.substr(0, str.length) == str; }
比较两个字符串是否相等,不区分大小写!
新闻热点
疑难解答
图片精选