Trimming Strings

[Total: 0    Average: 0/5]

This example will trim white spaces from the left and right sides.

Head Code:

<script>
function trim1(str)
{
  var i,j;
  i = 0;
  j=str.length-1;
  str = str.split("");
  while(i < str.length)
  {
    if(str[i]==" ")
    {
      str[i] = ""
    }
    else
    {
      break;
    }
    i++;
  }
  while(j > 0)
  {
    if(str[j]== " ")
    {
      str[j]=""
    }
    else
    {
      break;
    }
    j--;
  }
  return document.f1.t1.value = str.join("")
}
function trim2(_s)
{
  var pattern=/^s*(S+)s*$/;
  var _a=pattern.exec(_s);
  return document.f1.t1.value = RegExp.lastParen;
}
function trim3(_s)
{
  var S=0;
  var T=true;
  for(var i=0;i<_s.length;i++)
  {
    if(T&&_s[i]==" ")
      S=i;
    else
      T=false;
  }
  var E=_s.length-1;
  T=true;
  for(var i=(_s.length-1);i>=0;i--)
  {
    if(T&&_s[i]==" ")
      E=i;
    else
      T=false;
  }
  return document.f1.t1.value=_s.substr(S+1,E-(S+1));
}
</script>

Body Code:

<form name=f1>
Before:<input type=text name=t0 value="               1122            "><BR>
After:<input type=text name=t1><BR>
<input type=button onclick="trim1(this.form.t0.value)" value="Trim1">
<input type=button onclick="trim2(this.form.t0.value)" value="Trim2">
<input type=button onclick="trim3(this.form.t0.value)" value="Trim3">
</form>

Times Viewed: 0

Leave a Reply

Your email address will not be published. Required fields are marked *