Removing spaces at both ends of a string is a very common method for string processing. Unfortunately, JavaScript does not have these three methods, only we have customized them:
Step 1, add members to String
String.prototype.Trim = function(){ return Trim(this);}
String.prototype.LTrim = function(){return LTrim(this);}
String.prototype.RTrim = function(){return RTrim(this);}
Second Step, implement the method
function LTrim(str)
{
var i;
for(i=0;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, so that the code is clearer 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, "");
}