Javascript ucwords() Replacement

Since PHP is the primary language I use, I’m most familiar with all of it’s wonderful built-in functions, like ucwords(). I’ve used various code for a Javascript equivalent, and everytime I wind up with about 20 lines to do one simple thing. But I pieced this together from several sources today:

String.prototype.toProperCase = function(){
     return this.toLowerCase().replace(/\w+/g,function(s){
          return s.charAt(0).toUpperCase() + s.substr(1);
     })
}

I’m not the greatest Javascript programmer, and I never knew that I could add methods to the built-in String class; it’s much simpler than I had thought. This bit of code also shows how concise Javascript lets you get with inline functions. And in case it isn’t obvious, after that code, you could now do something as simple as this:

something = 'heRE ARE some crazy CApital letters';
alert(something.toProperCase()); // displays 'Here Are Some Crazy Capital Letters'

One Response to “Javascript ucwords() Replacement”

  1. Neil Says:

    I wrote something similar about 15 year ago using some hybrid BASIC that just didn’t catch on. It was pretty tricky and took twice as many lines of code. However, it did run pretty well on my IIc. If you need help with Javascript, let me know.

    10 PRINT “Hello, world!”
    20 END

Leave a Reply