it’s hokey, but it’s a nice basis for some other things. why didn’t i go looking for this last night when i was slamming my head against stupid code? ugh.
function trim(str)
{
while(‘’+str.charAt(0)==’ ‘)
str=str.substring(1,str.length);
while(‘’+str.charAt(str.length-1)==’ ‘)
str=str.substring(0,str.length-1);
return str;
}
Tags: web-programming

7 comments
Comments feed for this article
Trackback link
http://artlung.com/blog/2006/04/21/javascript-trim-function/trackback/
April 21, 2006 at 8:10 pm
natedavidr
if i’m not mistaken, that’s for trimming preceding spaces, right? darn the spaces! darn em!
April 22, 2006 at 8:30 am
Sassy
I am starting a pretty big AJAX project, and we are trying to decide to use a ‘framework’ vs straight Javascript. I am pushing for straight JS but the team is leaning towards the frameworks, which are admittedly easier to use. The problem I am running into is the lack of libraries in JS. You miss the little things like string.trim() and string.format(). Next week I am going to look into some various utility and string libs, if I find anything decent I’ll shoot you a link.
April 22, 2006 at 9:08 am
Joe Crawford
Nate, the code strips space characters from the beginning then the end of a string, then returns the result.
Sassy, I swear I was just reading about an effort to build something like PEAR or CPAN but for JavaScript. Somehow though, in my bleary eyed morning state, I can’t think of either a url or a way to search for it that works.
Not enough caffiene, perhaps!
April 22, 2006 at 1:10 pm
Joe Crawford
What I was thinking of I had read here, it’s openjsan.org. Though it might suck.
April 25, 2006 at 7:46 pm
Thogek
Depending on your version of JavaScript (i.e., regular expression support), you may also be able to do:
function TrimString(str) {
str = str.replace(/^[ ]+(.*)$/, ‘$1’); // Trims leading spaces
str = str.replace(/^(.*)[ ]+$/, ‘$1’); // Trims trailing spaces
return str;
}
August 2, 2006 at 8:14 pm
Kok Koon Leong
I like your javascript trim function. I have seen a number of similar code using regular expressions and tried some of them. They all work but yours is another refreshing take on ‘trim’.
That’s the beauty of programming – so many ways to solve one problem.
August 2, 2006 at 8:51 pm
Joe Crawford
I couldn’t agree more KKL.
Take care and happy programming!