Search
Winners

Win Prizes

Social Presence
Twitter Twitter LinkedIn YouTube Google

Like us on Facebook
Advertisements
Top Codes Author
Thu, 23-Oct-2014 Authors
All Time Authors
Satyapriyanayak
12160
Vishal@Neeraj
8240
Jayakumars
8120

Latest members | More ...


(Statistics delayed by 5 minutes)
 Codes

Trim function in JavaScript?

Poster
Posted by Poster under JavaScript on 3/1/2009 7:36:03 AM | Views : 22749 | Status : [Member]

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"


Found interesting? Add this to:



Comments or Responses

Posted by: K.Govindarao523@Gmail.Com on: 5/7/2014 | Level:Bronze | Status: [Member] | 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: [Microsoft_MVP] [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