Skip to content

Instantly share code, notes, and snippets.

@YanivHaramati
Created January 12, 2015 06:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YanivHaramati/493b170a6efb411dc7a6 to your computer and use it in GitHub Desktop.
Save YanivHaramati/493b170a6efb411dc7a6 to your computer and use it in GitHub Desktop.
capitalize a sentence assuming one space delimiter
// take the str parameter being passed and capitalize the first letter of each word.
// Words will be separated by only one space.
function capitalize(str) {
var upperLowerDiff = "a".charCodeAt(0) - "A".charCodeAt(0);
var toUpper = function(c) {
return String.fromCharCode(c.charCodeAt(0) - upperLowerDiff);
};
var isLower = function(c) {
return /[a-z]/g.test(c);
};
return str.split(' ')
.map(function (word) {
var firstLetter = word.charAt(0);
return (!isLower(firstLetter))
? word
: (word.length == 1)
? toUpper(firstLetter)
: toUpper(firstLetter) + word.substring(1);
})
.join(' ');
}
String.prototype.titleCase = function() {
return capitalize(this);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment