JavaScript ucwords
Uppercase the first character of every word in a string
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 19 | function ucwords (str) { // Uppercase the first character of every word in a string // // version: 1109.2015 // discuss at: http://phpjs.org/functions/ucwords // + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) // + improved by: Waldo Malqui Silva // + bugfixed by: Onno Marsman // + improved by: Robin // + input by: James (http://www.james-bell.co.uk/) // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // * example 1: ucwords('kevin van zonneveld'); // * returns 1: 'Kevin Van Zonneveld' // * example 2: ucwords('HELLO WORLD'); // * returns 2: 'HELLO WORLD' return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) { return $1.toUpperCase(); }); } |
Examples
» Example 1
Running
1 | ucwords('kevin van zonneveld'); |
Should return
1 | 'Kevin Van Zonneveld' |
» Example 2
Running
1 | ucwords('HELLO WORLD'); |
Should return
1 | 'HELLO WORLD' |
Dependencies
No dependencies, you can use this function standalone.
Open syntax issues
php.js uses JsLint to help us keep our code consistent and prevent some common bugs.
Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.
Authors
Thanks to the following developers, you get to have ucwords goodness in JavaScript.
I have modified the regex used so that it ignores spaces and numbers, new to regex so any hints, tips, changes etc.. are welcome
function ucwords(str)
{
str = str.toLowerCase(); //Optional
return (str).replace(/^([^\s0-9])|\s([^\s0-9])/g, function (l)
{
return l.toUpperCase();
});
}
@Jerry: A nice idea, but that only works with English letters. If we could boil it down a bit, we could incorporate XRegExp.com along with its excellent Unicode plug-in to determine whether something was lower case or not, but that would probably end up costing more performance to check for all the Unicode values (and it would need to take into account some languages which deviate from the Unicode case mapings). Off topic slightly, our function should really be made to work with locale_set_default (whenever that gets implemented!), at least when the "unicode.semantics" ini is on.
I prefer this slightly modified version as replacement function should ONLY be called when the regex finds suitable letters instead of suitable characters.
function ucwords(str) {
return (str + '').replace(/^[a-z]|\s[a-z]/g,
function ($1) {
return $1.toUpperCase();
}
);
}
@Robin: It wasn't hostility at all! I just didn't see your notice, so I was just stating what I said in a matter of fact way, not with any sarcasm or anything. And as you say, it was my mistake for missing your additional comment. We're really sorry if you were met with hostility earlier, but sometimes I think the lack of opportunity for clarification of intent may mistakenly give that impression; if you were met with genuine hostility, or we could have been more clear or more polite, our apologies certainly for that! And yes, we are eager to make JSLint fixes, so thank you very much for the function fixes! I'll see about applying them in Git now...
@Brett: Thanks for the feedback, but if you read the rest of my comment, you'll see I did not intend to change the function in any way, except to make it conform to the JSLint conventions, as shown by the "Open syntax issues."
"Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on."
If the previous statement no longer stands, I suggest you remove it from your website.
This isn't the first time I've tried to contribute to this site, and been met by hostility but thankfully, this will be the last, you may commence the group sigh of relief.
@Robin: Thanks for the submission, but besides differing in a variable name, your function looks identical to what we already have...
function ucwords(str) {
return (str + '').replace(/^(.)|\s(.)/g, function (m) {
return m.toUpperCase();
});
}
Now conforms to JSLint syntax conventions.
Great function - and picked up #1 on google search for what I was after. Saved me a host of time. Thanks
It doesn't work to me on Firefox 3, it returns the same input sentence (I've used a complete uppercase sentence)...
@ _argos: That's good enough for me :) I'm replacing the function and leave the original one here for future reference:
[CODE="Javascript"]
function ucwords( str ) {
// http://kevin.vanzonneveld.net
// + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
// * example 1: ucwords('kevin van zonneveld');
// * returns 1: 'Kevin Van Zonneveld'
return str.toLowerCase().replace(/\w+/g, function(s){
return s.charAt(0).toUpperCase() + s.substr(1);
});
}
[/CODE]
Hi Kevin, I'm making a benchmark of this function using RegExp an is 25%-30% more faster than your original function, this is the bechmark that I try:
[CODE="Javascript"]
// _argos's function
function ucwords_w ( str ) {
return str.replace(/^(.)|\s(.)/g, function ( $1 ) { return $1.toUpperCase ( ); } );
}
// Original function
function ucwords( str ) {
return str.toLowerCase().replace(/\w+/g, function(s){
return s.charAt(0).toUpperCase() + s.substr(1);
});
}
// BENCHMARK
var start;
start=new Date();
iterations = 10000;
while ( iterations-- ) {
ucwords('Kevin van Zonneveld');
ucwords('Waldo Malqui Silva');
ucwords('Alexa Valentina Malqui Cordova');
}
console.log('strrev = ' + ( (new Date())-start))
start=new Date();
iterations = 10000;
while ( iterations-- ) {
ucwords_w('Kevin van Zonneveld');
ucwords_w('Waldo Malqui Silva');
ucwords_w('Alexa Valentina Malqui Cordova');
}
console.log( 'strrev_w = ' + ( (new Date())-start ))
[/CODE]


Kevin van Zonneveld
8 Sep '10