Search

What the Quote?

"Breastmilk makes everything cooler!"

Mike Koenig

"Let me show you something that'll melt your face off like a Nazi!"

Chris Toohey

"That's gonna pop into my head in the middle of some meeting... I'll spray Gatorade all over the projector, and run to the restroom, hoping to not piss my chinos."

Tim Tripcony

« Javascript String.toProperCase | Main| Java is not my friend »

Update: Javascript String.toProperCase

Category show-n-tell thursday
I couldn't resist. Here's the updated Javascript function that propercases all words in a String, not just the first. Just insert a .push for each additional delimiter (i.e. quote, comma, pipe, etc.) you may wish to scan for, and the internal iteration function will uppercase the first character after each.

Object.extend(String.prototype, {
    toProperCase: function() {
        var strOriginalValue = this.toLowerCase();
        var strModifiedValue = strOriginalValue.slice(0,1).toUpperCase() + strOriginalValue.slice(1).toLowerCase();
        var arrDelimiters = new Array();
        arrDelimiters.push(' ');
        arrDelimiters.push('\\');
        arrDelimiters.push('(');
        arrDelimiters.each(
            function(strDelimiter) {
                var strTemporary = '';
                var strRemaining = strModifiedValue;
                var intDelimiterIndex = strRemaining.indexOf(strDelimiter);
                while (intDelimiterIndex > -1) {
                    var strBeforeDelimiter = strRemaining.slice(0,intDelimiterIndex);
                    var strAfterDelimiter = strRemaining.slice(intDelimiterIndex + 1);
                    strRemaining = strAfterDelimiter.slice(0,1).toUpperCase() + strAfterDelimiter.slice(1);
                    strTemporary += strBeforeDelimiter + strDelimiter;
                    intDelimiterIndex = strRemaining.indexOf(strDelimiter);
                }
                strModifiedValue = strTemporary + strRemaining;
            }
        );
        return strModifiedValue;
    }
});

Comments

Gravatar Image1 - Here's a non-prototype adaptation of a very compact, elegant solution that I found at { Link } (seems to be down at the moment, but it was working yesterday)

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