String.prototype Case Conversions - toTitleCase, toCapitalCase, anyStringToTitleCase.
There are numerous String.prototype
code examples for changing case that can be found, yet none seem to address the common issue where the string input is in all-capitals and is needed to output as "Capital case" or "Title Case" - the examples I've seen will simply result in returning the string still as all-caps.
Have chosen to follow the String nomenclature convention as described by .toLowerCase()
and .toUpperCase()
.
.toCapitalCase()
/* string.toCapitalCase()
Handles inputs:
UPPERCASE, "space separated".
eg: 'STRING TO CONVERT'.toCapitalCase() returns: 'String to convert'
*/
String.prototype.toCapitalCase = function() {
return this.charAt(0).toUpperCase() + this.slice(1).toLowerCase();
};
.toTitleCase()
/* string.toTitleCase()
Handles inputs:
UPPERCASE, "space separated".
eg: 'STRING TO CONVERT'.toTitleCase() returns: 'String To Convert'
*/
String.prototype.toTitleCase = function() {
return this.split(' ')
.map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
.join(' ');
};
.anyStringToTitleCase()
/* string.anyStringToTitleCase()
Handles inputs:
"space separated", camelCase, ClassCase, UPPERCASE, snake_case, dash-case, object.case.
eg: 'string-toConvert_has a.very ComplexStructure'.anyStringToTitleCase()
returns: 'String To Convert Has A Very Complex Structure'
*/
const STRING_DECAMELIZE_REGEXP = (/([a-z\d])([A-Z])/g);
const STRING_SEPARATORS_REGEXP = (/(\-|\_|\.)/g);
String.prototype.anyStringToTitleCase = function() {
return this.replace(STRING_DECAMELIZE_REGEXP, '$1 $2')
.replace(STRING_SEPARATORS_REGEXP, ' ')
.split(' ')
.map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
.join(' ');
};
Written by gentlefox
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#