Created
September 29, 2018 01:05
-
-
Save whoisryosuke/5b0d54926c997a6620945d780958ea74 to your computer and use it in GitHub Desktop.
Javascript / ES6 - Uppercase first letter of each word (2 ways) -- via: https://stackoverflow.com/a/4878800
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
function toTitleCase(str) { | |
return str.replace(/\w\S*/g, function(txt){ | |
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); | |
}); | |
} | |
// or in ES6: | |
var text = "foo bar loo zoo moo"; | |
const ucfirst = text => text.toLowerCase() | |
.split(' ') | |
.map((s) => s.charAt(0).toUpperCase() + s.substring(1)) | |
.join(' '); |
'This is a demo'.replace(/\b[a-zA-Z]/g, (match) => match.toUpperCase());
My two cents.
@Ltoya great code all-though it does not work with some french letters:
jérôme" => JéRôMe
Here's another take with regex that works with accents:
function toTitleCase(str) {
return str.replace(/(?:^|\s)\S/g, (match) => { return match.toUpperCase(); });
}
Example:
toTitleCase("jérôme gabriel")
Jérôme Gabriel
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@mulhoon, Yes, that's what I must have been looking for at the time. The gist clearly says it uppercases the first letter of each word, I don't know how I missed that. Just ignore my code.