I want to use a javascript function to capitalize the first letter of every word
eg:
THIS IS A TEST ---> This Is A Test
this is a TEST ---> Th
you can also use below approach using filter:
function Ucwords(str){
var words = str.split(' ');
var arr = [];
words.filter(function(val){
arr.push(val.charAt(0).toUpperCase()+ val.substr(1).toLowerCase());
})
console.log(arr.join(" ").trim());
return arr.join(" ").trim();
}
Ucwords("THIS IS A TEST") //This Is A Test
Ucwords("THIS ") //This
Here's a little one liner that I'm using to get the job done
var str = 'this is an example';
str.replace(/\b./g, function(m){ return m.toUpperCase(); });
but John Resig did a pretty awesome script that handles a lot of cases http://ejohn.org/blog/title-capitalization-in-javascript/
Update
ES6+ answer:
str.split(' ').map(s => s.charAt(0).toUpperCase() + s.slice(1)).join(' ');
There's probably an even better way than this. It will work on accented characters.
function capitalizeEachWord(str)
{
var words = str.split(" ");
var arr = [];
for (i in words)
{
temp = words[i].toLowerCase();
temp = temp.charAt(0).toUpperCase() + temp.substring(1);
arr.push(temp);
}
return arr.join(" ");
}
take a look at ucwords from php.js - this seems to be kind of what you're looking for. basically, it's:
function ucwords (str) {
return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {
return $1.toUpperCase();
});
}
note that THIS IS A TEST
will return THIS IS A TEST
so you'll have to use it like this:
var oldstring = "THIS IS A TEST";
var newstring = ucwords(oldstring.toLowerCase());
or modify the function a bit:
function ucwords (str) {
str = (str + '').toLowerCase();
return str.replace(/^([a-z])|\s+([a-z])/g, function ($1) {
return $1.toUpperCase();
});
}
var oldstring = "THIS IS A TEST";
var newstring = ucwords(oldstring); // This Is A Test
This will capitalize every word seperated by a space or a dash
function capitalize(str){
str = str.toLowerCase();
return str.replace(/([^ -])([^ -]*)/gi,function(v,v1,v2){ return v1.toUpperCase()+v2; });
}
Examples :
etc
If you don't mind using a library, you could use Sugar.js capitalize()
capitalize( all = false ) Capitalizes the first character in the string and downcases all other letters. If all is true, all words in the string will be capitalized.
Example:
'hello kitty'.capitalize() -> 'Hello kitty'
'hello kitty'.capitalize(true) -> 'Hello Kitty'