Created
January 12, 2015 06:22
-
-
Save YanivHaramati/493b170a6efb411dc7a6 to your computer and use it in GitHub Desktop.
capitalize a sentence assuming one space delimiter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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