`
chun521521
  • 浏览: 276726 次
  • 性别: Icon_minigender_1
  • 来自: 长春
社区版块
存档分类
最新评论

js实现 trim,replaceAll,startWith,endWith

    博客分类:
  • js
 
阅读更多

 

 

/**
 * 对trim()的扩展
 */
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, "");
};


/**
 * 对startWith()的扩展
 */
String.prototype.startWith=function(str){
 if(str==null||str==""||this.length==0||str.length>this.length){
  return false;
 }
 return (this.substr(0,str.length) == str);
};
/**
 * 对endWith()的扩展
 */
String.prototype.endWith = function(str){
 if(str==null||str==""||this.length==0||str.length > this.length){
  return false;
 }
 return(this.substring(this.length-str.length) == str);
};
/**
 * 对replaceAll()的扩展
 */
String.prototype.replaceAll = function(s1,s2) {
    var raRegExp = new RegExp(s1.replace(/([\(\)\[\]\{\}\^\$\+\-\*\?\.\"\'\|\/\\])/g,"\\$1"),"ig");
    return this.replace(raRegExp,s2);
};

 

//替换占位符

String.prototype.format = function(){
 if(arguments.length==0){
  return this;
 }
 for(var s=this, i=0; i<arguments.length; i++){
  s = s.replace(new RegExp("\\{"+i+"\\}","g"), arguments[i]);
 }
 return s;
};

 

 

  • 大小: 9.4 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics