Copy Code code as follows:
Remove the header space of the string (left space)
function LTrim (str) {
var i;
for (i=0;i<str.length; i++) {
if (Str.charat (i)!= "") break;
}
str = str.substring (i,str.length);
return str;
}
Remove the trailing space of the string (right space)
function RTrim (str) {
var i;
for (i=str.length-1;i>=0;i--) {
if (Str.charat (i)!= "") break;
}
str = str.substring (0,i+1);
return str;
}
Remove the trailing space of the string (left and right)
function Trim (str) {
Return LTrim (RTrim (str));
}
Delete all functions in a string
JS Delete string space function
Copy Code code as follows:
function Jtrim (str)
{
var i = 0;
var len = str.length;
if (str = = "") return (str);
j = len-1;
Flagbegin = true;
Flagend = true;
while ((Flagbegin = = True) && (i< len)
{
if (Str.charat (i) = = "")
{
i=i+1;
Flagbegin=true;
}
Else
{
Flagbegin=false;
}
}
while ((flagend== true) && (j>=0)
{
if (Str.charat (j) = "")
{
J=j-1;
Flagend=true;
}
Else
{
Flagend=false;
}
}
if (i > J) return ("");
Trimstr = str.substring (i,j+1);
return trimstr;
}
The above method is useless to the regular, we use the regular expression to try
Regular substitution space
Copy Code code as follows:
Remove middle space in string
String.prototype.Trim = function () {
Return This.replace (/(^s*) | ( s*$)/g, "");
}
Remove space on left side of string
String.prototype.LTrim = function () {
Return This.replace (/(^s*)/g, "");
}
Remove the right space on the string
String.prototype.RTrim = function () {
Return This.replace (/(s*$)/g, "");
}
Remove all spaces
Copy Code code as follows:
var s = "ASD ddd bbb SSS";
var reg =/s/g;
var ss = S.replace (Reg, "");
Alert (ss);
Remove all spaces in the string (including intermediate spaces, and set the 2nd argument to: G)
Copy Code code as follows:
function Trim (Str,is_global)
{
var result;
result = Str.replace (/(^s+) | ( s+$)/g, "");
if (is_global.tolowercase () = = "G")
result = Result.replace (/s/g, "");
return result;
}