-
-
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.
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
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(); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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()
})
}