JavaScript custom methods to achieve trim of Ltrim of Rtrim of function

  • 2020-03-26 21:45:27
  • OfStack

Removing the Spaces at both ends of the string is a very common method of string handling. It is a pity that JavaScript does not have these three methods, only we customize:
Step 1, add a member to String
 
String.prototype.Trim = function(){ return Trim(this);} 
String.prototype.LTrim = function(){return LTrim(this);} 
String.prototype.RTrim = function(){return RTrim(this);} 

The second step is to implement the method
 
function LTrim(str) 
{ 
var i; 
for(i=0;i<str.length;i++) 
{ 
if(str.charAt(i)!=" "&&str.charAt(i)!=" ")break; 
} 
str=str.substring(i,str.length); 
return str; 
} 
function RTrim(str) 
{ 
var i; 
for(i=str.length-1;i>=0;i--) 
{ 
if(str.charAt(i)!=" "&&str.charAt(i)!=" ")break; 
} 
str=str.substring(0,i+1); 
return str; 
} 
function Trim(str) 
{ 
return LTrim(RTrim(str)); 
} 

Of course, you can also use regular expressions to make your code cleaner and more efficient,
 
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, ""); 
} 

Related articles: