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

John Saunders
  • 160,644
  • 26
  • 247
  • 397
David
  • 177
  • 1
  • 1
  • 3
  • http://stackoverflow.com/questions/1026069/capitalize-the-first-letter-of-string-in-javascript – reader_1000 Sep 19 '11 at 06:52
  • Turn to lower case, cut into individual words by splitting by whitespace, toUpperCase() on the first char of each word. –  Sep 19 '11 at 06: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 '11 at 07:29
  • possible duplicate of [Convert string to title case with javascript](http://stackoverflow.com/questions/196972/convert-string-to-title-case-with-javascript) – Ja͢ck Jun 11 '12 at 06:01
  • kinda the point of CSS right... to "style" the dom? text-transform: capitalize; – worked Jun 21 '18 at 15:42

9 Answers9

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.

Stephen
  • 7,994
  • 9
  • 44
  • 73
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(" ");
}
twernt
  • 20,271
  • 5
  • 32
  • 41
reader_1000
  • 2,473
  • 17
  • 15
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();
  });
Andrew D.
  • 8,130
  • 3
  • 21
  • 23
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(' ');

}
DefionsCode
  • 483
  • 4
  • 8
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

Lunfel
  • 2,499
  • 21
  • 29
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'
andersh
  • 8,105
  • 6
  • 39
  • 30
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
VIJAY P
  • 1,363
  • 1
  • 12
  • 14
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
oezi
  • 51,017
  • 10
  • 98
  • 115
-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);
    }