Removing the spaces at each end of the string is a very common method of string processing, and unfortunately JavaScript does not have these three methods, only we have customized:
Step 1th, add members to string
Copy Code code as follows:
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
Copy Code code as follows:
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 so that the code is clearer and more efficient,
Copy Code code as follows:
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, "");
}