Description :

I am showing use of Trim functions for strings using Javascript.

The main three types of Trim are:
  1. Left Trim
  2. Right Trim
  3. Trim All

1. Left Trim :
  • It will trim leading white spaces characters from a given string.
  • Pass a parameter for string in which we perform a Left Trim operation.
  • Returns a string after removing the leading white spaces from a string.

Example :

Suppose a string is " Ghanashyam".

Here 3 white spaces preced the Ghanashyam.

So using this, we can remove that white space and then the string will be "Ghanashyam".

function LeftTrim(LeftTrim_String)
{
var RegExpobj = /^(\s*)(\b[\w\W]*)$/;
if(RegExpobj.test(LeftTrim_String))
{
//remove leading a whitespace characters From "LeftTrim_String"
LeftTrim_String = LeftTrim_String.replace(RegExpobj, '$2');
}
return LeftTrim_String;
}

2. Right Trim :

  • It will Trim trailing white space characters from a given string.

  • Pass a parameter for a string in which we perform a Right Trim operation.

  • Returns a string after removing trailing white spaces from a string.

Example :

Suppose a string is "Ghanashyam ".

There are 3 white spaces after the Ghanashyam.

So using the following, we can remove that white space and then the string will be "Ghanashyam".


function RightTrim(RightTrim_String)
{
var RegExpobj = /^([\w\W]*)(\b\s*)$/;
if(RegExpobj.test(RightTrim_String))
{
//remove leading a whitespace characters From "RightTrim_String"
RightTrim_String = RightTrim_String.replace(RegExpobj, '$1');
}
return RightTrim_String;
}


3. Trim All :

  • Will Trim leading & trailing white space characters from a given string.

  • Pass a parameter for a string in which we perform a Trim All operation.

  • Returns a string after removing leading & trailing white spaces from a string.

Example :

Suppose String Is " Ghanashyam ".

Here there are 3 white spaces before the Ghanashyam & after the Ghanashyam.

So using this, we can remove the white spaces and then the string will be "Ghanashyam".

function TrimAll(TrimAll_String)
{
var RegExpobj = /^(\s*)$/;

//Check For All Whitespaces
if(RegExpobj.test(TrimAll_String))
{
TrimAll_String = TrimAll_String.replace(RegExpobj, '');
if( TrimAll_String.length == 0)
return TrimAll_String;
}

//Check For Leading & Trailing Whitespaces
RegExpobj = /^(\s*)([\W\w]*)(\b\s*$)/;
if(RegExpobj.test(TrimAll_String))
{
//Remove Leading And Trailing White Space Characters
TrimAll_String = TrimAll_String.replace(RegExpobj, '$2');
}
return TrimAll_String;
}