Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I capitalize the first letter of each word in a string using JavaScript?

People also ask

How do you capitalize text in JavaScript?

The toUpperCase() method converts the string to uppercase. Here, str. charAt(0). toUpperCase(); gives J.

How do you make each word start with a capital letter?

To use a keyboard shortcut to change between lowercase, UPPERCASE, and Capitalize Each Word, select the text and press SHIFT + F3 until the case you want is applied.

How do you capitalize every word in a string?

Use title() to capitalize the first letter of each word in a string in python. Python Str class provides a member function title() which makes each word title cased in string. It means, it converts the first character of each word to upper case and all remaining characters of word to lower case.


You are not assigning your changes to the array again, so all your efforts are in vain. Try this:

function titleCase(str) {
   var splitStr = str.toLowerCase().split(' ');
   for (var i = 0; i < splitStr.length; i++) {
       // You do not need to check if i is larger than splitStr length, as your for does that for you
       // Assign it back to the array
       splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);     
   }
   // Directly return the joined string
   return splitStr.join(' '); 
}

document.write(titleCase("I'm a little tea pot"));

You are making complex a very easy thing. You can add this in your CSS:

.capitalize {
    text-transform: capitalize;
}

In JavaScript, you can add the class to an element

 document.getElementById("element").className = "capitalize";

ECMAScript 6 version:

const toTitleCase = (phrase) => {
  return phrase
    .toLowerCase()
    .split(' ')
    .map(word => word.charAt(0).toUpperCase() + word.slice(1))
    .join(' ');
};

let result = toTitleCase('maRy hAd a lIttLe LaMb');
console.log(result);

I think this way should be faster; cause it doesn't split string and join it again; just using regex.

var str = text.toLowerCase().replace(/(^\w{1})|(\s{1}\w{1})/g, match => match.toUpperCase());

Explanation:

  1. (^\w{1}): match first char of string
  2. |: or
  3. (\s{1}\w{1}): match one char that came after one space
  4. g: match all
  5. match => match.toUpperCase(): replace with can take function, so; replace match with upper case match

Shortest One Liner (also extremely fast):

 text.replace(/(^\w|\s\w)/g, m => m.toUpperCase());

Explanation:

  • ^\w : first character of the string
  • | : or
  • \s\w : first character after whitespace
  • (^\w|\s\w) Capture the pattern.
  • g Flag: Match all occurrences.

If you want to make sure the rest is in lowercase:

text.replace(/(^\w|\s\w)(\S*)/g, (_,m1,m2) => m1.toUpperCase()+m2.toLowerCase())

Example usage:

// Create a reusable function:
const toTitleCase = str => str.replace(/(^\w|\s\w)/g, m => m.toUpperCase());

// Call the function:
const myStringInTitleCase = toTitleCase(myString);

If you can use a third-party library then Lodash has a helper function for you.

https://lodash.com/docs/4.17.3#startCase

_.startCase('foo bar');
// => 'Foo Bar'

_.startCase('--foo-bar--');
// => 'Foo Bar'

_.startCase('fooBar');
// => 'Foo Bar'

_.startCase('__FOO_BAR__');
// => 'FOO BAR'
<script src="https://cdn.jsdelivr.net/lodash/4.17.3/lodash.min.js"></script>