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;
}
});
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
function toProperCase(str) {
return str.toLowerCase().replace(
/\w+/g,function(s){ return s.charAt(0).toUpperCase() + s.substr(1); }
)
}
Posted by Ted At 05:18:51 PM On 09/30/2006 | - Website - |