Use PHP functions in JavaScript

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
function ucwords(str) {
    // Uppercase the first character of every word in a string  
    // 
    // version: 1008.1718
    // 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
    // *     example 1: ucwords('kevin van zonneveld');    // *     returns 1: 'Kevin Van Zonneveld'
    // *     example 2: ucwords('HELLO WORLD');
    // *     returns 2: 'HELLO WORLD'
    return (str + '').replace(/^(.)|\s(.)/g, function ($1) {
        return $1.toUpperCase();    });
}
external links: original PHP docs | raw js source

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.

Comments

Add Comment
Use:
[CODE]
your_stuff('here');
[/CODE]
for proper code formatting
By submitting code here you are allowing us to use it in php.js hence dual licensing it under the MIT and GPL licenses

Gravatar
James
Aug 11th Permalink

q  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();
    });
}

Gravatar
Brett Zamir
Apr 28th Permalink

q  @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.

Gravatar
Jerry
Apr 27th Permalink

q  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();
     }
);
}

Gravatar
Brett Zamir
Jan 29th Permalink

q  @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...

Gravatar
Robin
Jan 28th Permalink

q  @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.

Gravatar
Brett Zamir
Jan 26th Permalink

q  @Robin: Thanks for the submission, but besides differing in a variable name, your function looks identical to what we already have...

Gravatar
Robin
Jan 25th Permalink

q  

function ucwords(str) {
	return (str + '').replace(/^(.)|\s(.)/g, function (m) {
		return m.toUpperCase();
	});
}



Now conforms to JSLint syntax conventions.

Gravatar
Tony
Jan 11th Permalink

q  Great function - and picked up #1 on google search for what I was after. Saved me a host of time. Thanks

Gravatar
Alessandro
31 Jul '08 Permalink

q  It doesn't work to me on Firefox 3, it returns the same input sentence (I've used a complete uppercase sentence)...

Gravatar
Kevin van Zonneveld
31 Jan '08 Permalink

q  @ _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]

Gravatar
_argos
31 Jan '08 Permalink

q  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]

Gravatar
Kevin van Zonneveld
19 Jan '08 Permalink

q  @ Lars: You're welcome ;)

Gravatar
Lars
19 Jan '08 Permalink

q  thanks!


Contribute a New function