16

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 ---> This Is A Test
this is a test ---> This Is A Test

What would be a simple javascript function

5
  • Turn to lower case, cut into individual words by splitting by whitespace, toUpperCase() on the first char of each word.
    – user684934
    Sep 19, 2011 at 6:54
  • 2
    @reader_1000: that question is about uppercasing just the first char of a string while this is about uoppercasing the first char of every word (wich is way more complicated and needs a different solution)
    – oezi
    Sep 19, 2011 at 7:29
  • possible duplicate of Convert string to title case with javascript
    – Ja͢ck
    Jun 11, 2012 at 6:01
  • kinda the point of CSS right... to "style" the dom? text-transform: capitalize;
    – worked
    Jun 21, 2018 at 15:42

9 Answers 9

35

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.

2
  • 4
    I love how simple and succinct this one is. Nov 26, 2013 at 0:29
  • try the updated answer. sadly \b won't pick special chars
    – Stephen
    Nov 19, 2015 at 17:27
10
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(" ");
}
0
6
"tHiS iS a tESt".replace(/[^\s]+/g, function(str){ 
    return str.substr(0,1).toUpperCase()+str.substr(1).toLowerCase();
  });

Other variant:

"tHiS iS a tESt".replace(/(\S)(\S*)/g, function($0,$1,$2){ 
    return $1.toUpperCase()+$2.toLowerCase();
  });
4

This is a simple solution that breaks down the sentence into an array, then loops through the array creating a new array with the capitalized words.

 function capitalize(str){

  var strArr = str.split(" ");
  var newArr = [];

  for(var i = 0 ; i < strArr.length ; i++ ){

    var FirstLetter = strArr[i].charAt(0).toUpperCase();
    var restOfWord = strArr[i].slice(1);

    newArr[i] = FirstLetter + restOfWord;

  }

  return newArr.join(' ');

}
0
1

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
0
1

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 :

  • i lOvE oRanges => I Love Oranges
  • a strAnge-looKing syntax => A Strange-Looking Syntax

etc

1

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'
1

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
-1
{
        String s = "this is for testing";
        String sw[] = s.split("\\s");
        String newS = "";
        for(int i=0; i<=sw.length-1; i++)
        {
            String first = sw[i].substring(0,1);
            String last = sw[i].substring(1);
            newS+= first.toUpperCase()+last+" ";
            
        }
        System.out.println(newS);
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.