Skip to content

Instantly share code, notes, and snippets.

@rickycheers
Created January 15, 2013 19:45
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save rickycheers/4541395 to your computer and use it in GitHub Desktop.
Save rickycheers/4541395 to your computer and use it in GitHub Desktop.
ucwords in JavaScript - Equivalent to PHP's ucwords() Returns a string with the first letter in upper case of each word.
String.prototype.ucwords = function() {
str = this.toLowerCase();
return str.replace(/(^([a-zA-Z\p{M}]))|([ -][a-zA-Z\p{M}])/g,
function(s){
return s.toUpperCase();
});
};
@JorisDebonnet
Copy link

JorisDebonnet commented Oct 12, 2020

Careful though, that last one doesn't work in Safari. For some reason, it doesn't support lookbehind regex.
So I am now using (' '+str).replace(/ [\w]/g, a => a.toLocaleUpperCase()).trim(); ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment