js实现 trim,replaceAll,startWith,endWith

 

 

/**
 * 对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);
};

 

 

 

 

你可能感兴趣的:(replaceAll)