Skip to content

Instantly share code, notes, and snippets.

@rodrigojusto
Forked from rickycheers/ucwords.js
Created October 18, 2017 20:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rodrigojusto/a193f9595f9d814ca6a9bdda91172f3a to your computer and use it in GitHub Desktop.
Save rodrigojusto/a193f9595f9d814ca6a9bdda91172f3a 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();
});
};
@rodrigojusto
Copy link
Author

module.exports = function ucwords (str) {
// discuss at: http://locutus.io/php/ucwords/
// original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
// improved by: Waldo Malqui Silva (http://waldo.malqui.info)
// improved by: Robin
// improved by: Kevin van Zonneveld (http://kvz.io)
// bugfixed by: Onno Marsman (https://twitter.com/onnomarsman)
// bugfixed by: Cetvertacov Alexandr (https://github.com/cetver)
// input by: James (http://www.james-bell.co.uk/)
// example 1: ucwords('kevin van zonneveld')
// returns 1: 'Kevin Van Zonneveld'
// example 2: ucwords('HELLO WORLD')
// returns 2: 'HELLO WORLD'
// example 3: ucwords('у мэри был маленький ягненок и она его очень любила')
// returns 3: 'У Мэри Был Маленький Ягненок И Она Его Очень Любила'
// example 4: ucwords('τάχιστη αλώπηξ βαφής ψημένη γη, δρασκελίζει υπέρ νωθρού κυνός')
// returns 4: 'Τάχιστη Αλώπηξ Βαφής Ψημένη Γη, Δρασκελίζει Υπέρ Νωθρού Κυνός'
return (str + '')
.replace(/^(.)|\s+(.)/g, function ($1) {
return $1.toUpperCase()
})
}

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