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 :
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 :

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 :

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;
}