Trim function in JavaScript?

Poster
Posted by Poster under JavaScript category on | Views : 28032
Below is the Trim function that can be used to trim the white space from a string.

// Trim function in javascript 
function Trim(str)
{
while (str.substring(0,1) == ' ') // check for white spaces from beginning
{
str = str.substring(1, str.length);
}
while (str.substring(str.length-1, str.length) == ' ') // check white space from end
{
str = str.substring(0,str.length-1);
}

return str;
}


You can use this function like below
var str = "            sampe          ";
str = Trim(str);


The value of result will be "sample"

Comments or Responses

Posted by: kgovindarao523-21772 on: 5/7/2014 Level:Bronze | Status: [Member] [MVP] | Points: 10
Hi,
Why we need to write this code to trim the spaces before & after the string?
There is a predefined javascript function is there for it.

inputstring.trim()

why dont you use this.
in your case:
str.trim().


Posted by: Sheonarayan on: 5/7/2014 Level:HonoraryPlatinum | Status: [Administrator] | Points: 10
Good point Govind. This post was written in 2009(almost 5 years back) and Trim() function might not be available at that time.

Login to post response