SoFunction
Updated on 2025-02-28

Several ways to remove left and right spaces in js

//Recon ’s idea:
//-------------
//Remove the space on the left side of the string
function ltrim(str)
{
if ((0) == " ")
{
//If the first character on the left of the string is a space
str = (1);//Remove spaces from the string
//This sentence can also be changed to str = (1, );
str = ltrim(str);   //Recursive call
}
return str;
}

//Remove the space on the right side of the string
function rtrim(str)
{
var ilength;

ilength = ;
if ((ilength - 1) == " ")
{
//If the first character on the right side of the string is a space
str = (0, ilength - 1);//Remove spaces from the string
//This sentence can also be changed to str = (0, ilength - 1);
str = rtrim(str);   //Recursive call
}
return str;
}

//Remove the spaces on both sides of the string
function trim(str)
{
return ltrim(rtrim(str));
}

//The idea of ​​5337 on rainy day:
//----------------
function alltrim(a_strvarcontent)
{
  var pos1, pos2, newstring;

  pos1 = 0;
  pos2 = 0;
  newstring = ""

  if ( a_strvarcontent.length > 0 )
  {
    for( i=0; i<=a_strvarcontent.length; i++)
//recon: This sentence should have an error and should be changed to:
  //for( i=0; i<a_strvarcontent.length; i++)
    {
        if ( a_strvarcontent.charat(i) == " " )
          pos1 = pos1 + 1;
        else
          break;   
    }

    for( i=a_strvarcontent.length; i>=0 ; i--)
//recon: This sentence should have an error and should be changed to:
  //for( i=a_strvarcontent.length-1; i>=0 ; i--)
    {
        if ( a_strvarcontent.charat(i) == " " )
          pos2 = pos2 + 1;
        else
          break;   
    }

    newstring = a_strvarcontent.substring(pos1, a_strvarcontent.length-pos2)

}

  return newstring;

}

//hooke’s idea:
//-------------
function jtrim(sstr)
{
var astr="";
var dstr="";
var flag=0;
for (i=0;i<;i++)
  {if (((i)!=' ')||(flag!=0)) 
  {dstr+=(i);
  flag=1;
    }
  }
flag=0;
for (i=-1;i>=0;i--)
  {if (((i)!=' ')||(flag!=0)) 
  {astr+=(i);
  flag=1;
    }
  }
dstr="";
for (i=-1;i>=0;i--) dstr+=(i);
return dstr;
}
Why not use regular expressions?
 = function()
{
     return (/(^\s*)|(\s*$)/g, "");
}