Skip to content

Instantly share code, notes, and snippets.

@whoisryosuke
Created September 29, 2018 01:05
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • 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(' ');
@eloff
Copy link

eloff commented Nov 28, 2018

Simpler? const toTitleCase = s => s.substr(0, 1).toUpperCase() + s.substr(1).toLowerCase();

@mulhoon
Copy link

mulhoon commented Aug 1, 2019

Hi @eloff that would only uppercase the first letter of the whole sentence, not each word.

@eloff
Copy link

eloff commented Aug 1, 2019

@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.

@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