Skip to content

Instantly share code, notes, and snippets.

@whoisryosuke
Created September 29, 2018 01:05
Show Gist options
  • Save whoisryosuke/5b0d54926c997a6620945d780958ea74 to your computer and use it in GitHub Desktop.
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
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(' ');
@LTroya
Copy link

LTroya commented Jan 7, 2020

'This is a demo'.replace(/\b[a-zA-Z]/g, (match) => match.toUpperCase());

My two cents.

@flahol
Copy link

flahol commented Apr 8, 2020

@Ltoya great code all-though it does not work with some french letters:
jérôme" => JéRôMe

@semiaddict
Copy link

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