Married,moved,and getting it together.

JavaScript trim() function

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)==' ') {
    while(''+str.charAt(str.length-1)==' ') {
    return str;

seven comments so far...

if i’m not mistaken, that’s for trimming preceding spaces, right? darn the spaces! darn em!

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.

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!

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;

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.