Married, moved, and getting it together.

JavaScript trim() function 2006 Apr 21

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;
}
Joe Crawford blogged this at 2:42pm in 2006 in April. The 21st was a Friday. You are reading this 12 years later. Make a public comment. There are 7 comments Tweet. Direct message. Send email. It has hashtags→ .

Comments: 7

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!

What I was thinking of I had read here, it’s openjsan.org. Though it might suck.

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

Kok Koon Leong

August 2, 2006 8:14pm

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.

I couldn’t agree more KKL.

Take care and happy programming!

Leave a Reply

Comments Open; Trackbacks Open.