Home > dev, Javascript, jQuery, open source, Tech > Uppercase Words in a JS String

Uppercase Words in a JS String

I ran into a problem today where our geo coder returns city names in all uppercase. Obviously this doesn’t look very good when you print it out to the screen so I wanted to make it pretty. A good example is Young America, MN. We get “YOUNG AMERICA”.. Here’s a quick way to clean it up using jQuery:

$.map("YOUNG AMERICA".split(" "), 
        return s.charAt(0).toUpperCase() + s.toLowerCase().slice(1); 
).join(" ");

Explode the string into an array by splitting on the space, map that array into a function that returns the first character uppercased and the remaining characters in lower case. Then join the outputted array by a space.

This converts “young america” to “Young America”.

  1. April 7, 2011 at 4:11 pm

    This strikes me as pretty inefficient; what’s wrong with using a CSS property for text-transform: capitalize?

    • April 7, 2011 at 4:14 pm

      Because it doesn’t always wind up in HTML. Sometimes it gets bubbled up to a UIAlertView in Objective-C which doesn’t have CSS..

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: