PHP's ucwords in JavaScript

How to use

You you can install via yarn add locutus and require this function via const ucwords = require('locutus/php/strings/ucwords').

It is important to use a bundler that supports tree-shaking so that you only ship the functions that you actually use to your browser, instead of all of Locutus, which is massive. Examples are: Parcel, webpack, or rollup.js. For server-side use this is typically less of a concern.

Examples

Please note that these examples are distilled from test cases that automatically verify our functions still work correctly. This could explain some quirky ones.

#codeexpected result
1ucwords('kevin van zonneveld')'Kevin Van Zonneveld'
2ucwords('HELLO WORLD')'HELLO WORLD'
3ucwords('у мэри был маленький ягненок и она его очень любила')'У Мэри Был Маленький Ягненок И Она Его Очень Любила'
4ucwords('τάχιστη αλώπηξ βαφής ψημένη γη, δρασκελίζει υπέρ νωθρού κυνός')'Τάχιστη Αλώπηξ Βαφής Ψημένη Γη, Δρασκελίζει Υπέρ Νωθρού Κυνός'

Here’s what our current JavaScript equivalent to PHP's ucwords looks like.

module.exports = function ucwords(str) {
// discuss at: https://locutus.io/php/ucwords/
// original by: Jonas Raoni Soares Silva (https://www.jsfromhell.com)
// improved by: Waldo Malqui Silva (https://waldo.malqui.info)
// improved by: Robin
// improved by: Kevin van Zonneveld (https://kvz.io)
// bugfixed by: Onno Marsman (https://twitter.com/onnomarsman)
// bugfixed by: Cetvertacov Alexandr (https://github.com/cetver)
// input by: James (https://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()
})
}

A community effort

Not unlike Wikipedia, Locutus is an ongoing community effort. Our philosophy follows The McDonald’s Theory. This means that we assimilate first iterations with imperfections, hoping for others to take issue with-and improve them. This unorthodox approach has worked very well to foster fun and fruitful collaboration, but please be reminded to use our creations at your own risk. THE SOFTWARE IS PROVIDED "AS IS" has never been more true than for Locutus.

Now go and: [ View on GitHub | Edit on GitHub | View Raw ]


« More PHP strings functions


Star