Friday, October 21, 2011

JavaScript CamelCase string conversion to Proper Case

I ran into a case where I wanted to be able to reverse a CamelCase string to Proper Case format. Without using regex, due to the amount of time it would take for regex to make the replacement, I built up a function to convert a CamelCased string with the most likely proper result possible.

This function will add a space before a capital letter if it is not the first letter in the sentence, if the following character is not a capital (allow abbreviations/acronyms) and if the previous character was not a space (unlikely to be used, but allows for partial camel cased strings to be corrected). Unfortunately this function will not be able to detect a single letter capital word as an independent work, like 'I'. Since it's less common that 'I' would be used in a variable, when compared to an acronym or abbreviation, this was decided to be the lesser evil of errors.



String.prototype.camelToProper = function () {
if (this == null || this == "") {
return this;
}
var newText = "";
var characters = this.split("");
for (var i = 0; i < characters.length; i++) {
if (characters[i] == characters[i].toUpperCase()
&& i != 0
&& !(characters[i + 1] == characters[i + 1].toUpperCase())
&& characters[i - 1] != " ") {
newText += " ";
}
newText += characters[i];
}

return newText;
}

Stumble Upon ToolbarDigg this Post This to FacebookShare on Facebook Tweet Me

No comments:

Post a Comment