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(" "),
function(s){
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”.
Categories: dev, Javascript, jQuery, open source, Tech
This strikes me as pretty inefficient; what’s wrong with using a CSS property for text-transform: capitalize?
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..