JavaScript: CamelCase string conversion to Proper Case

in #javascript7 years ago

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;
}```
Sort:  

Hi! I am a robot. I just upvoted you! I found similar content that readers might be interested in:
http://awhitehat.blogspot.ca/

Good job bot, you found my blog post.

Congratulations @irrelevant! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

Award for the number of upvotes received

Click on any badge to view your own Board of Honnor on SteemitBoard.
For more information about SteemitBoard, click here

If you no longer want to receive notifications, reply to this comment with the word STOP

By upvoting this notification, you can help all Steemit users. Learn how here!