admin管理员组

文章数量:1125883

I'm trying to write a function that capitalizes the first letter of every word in a string (converting the string to title case).

For instance, when the input is "I'm a little tea pot", I expect "I'm A Little Tea Pot" to be the output. However, the function returns "i'm a little tea pot".

This is my code:

function titleCase(str) {
  var splitStr = str.toLowerCase().split(" ");

  for (var i = 0; i < splitStr.length; i++) {
    if (splitStr.length[i] < splitStr.length) {
      splitStr[i].charAt(0).toUpperCase();
    }

    str = splitStr.join(" ");
  }

  return str;
}

console.log(titleCase("I'm a little tea pot"));

I'm trying to write a function that capitalizes the first letter of every word in a string (converting the string to title case).

For instance, when the input is "I'm a little tea pot", I expect "I'm A Little Tea Pot" to be the output. However, the function returns "i'm a little tea pot".

This is my code:

function titleCase(str) {
  var splitStr = str.toLowerCase().split(" ");

  for (var i = 0; i < splitStr.length; i++) {
    if (splitStr.length[i] < splitStr.length) {
      splitStr[i].charAt(0).toUpperCase();
    }

    str = splitStr.join(" ");
  }

  return str;
}

console.log(titleCase("I'm a little tea pot"));

Share Improve this question edited Jul 29, 2020 at 0:33 Peter Mortensen 31.6k22 gold badges109 silver badges133 bronze badges asked Sep 15, 2015 at 14:52 slurrrslurrr 2,7542 gold badges12 silver badges11 bronze badges 8
  • That does not look like it capitalizes the first letter of just a string. Or do you mean you want to capitalize each word contained in the string. – epascarello Commented Sep 15, 2015 at 14:54
  • 3 You are not assigining your capitalisation to your result, the splitStr[i].charAt(0).toUpperCase(); is going to void. You need to do splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1); – somethinghere Commented Sep 15, 2015 at 14:54
  • 1 You should tell us first. What is wrong with that function? What is the expected result and what does it return instead? – Sebastian Simon Commented Sep 15, 2015 at 14:55
  • 6 Like the title says, I am trying to capitalize the first letter of each word in the string. I don't appreciate the downvotes or the negativity on a forum that is supposed to be supportive in nature. @somethinghere - Thank you for your response. – slurrr Commented Sep 15, 2015 at 21:45
  • 2 @slurr don't let it get to you too much, sometimes the people here can be a bit nitpicky about wording. Next time, try to be as precise as possible and you will probably receive a better response. Take it as a learning experience, so welcome to Stack Overflow and don't hold grudges (: – somethinghere Commented Sep 15, 2015 at 21:49
 |  Show 3 more comments

49 Answers 49

Reset to default 1 2 Next 250

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);

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:

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

console.log(toTitleCase("heLLo worLd"));

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

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>

In ECMAScript 6, a one-line answer using the arrow function:

const captialize = words => words.split(' ').map( w =>  w.substring(0,1).toUpperCase()+ w.substring(1)).join(' ')

ECMAScript 6 version:

title
    .split(/ /g).map(word =>
        `${word.substring(0,1).toUpperCase()}${word.substring(1)}`)
    .join(" ");
text-transform: capitalize;

CSS has got it :)

本文标签: How can I capitalize the first letter of each word in a string using JavaScriptStack Overflow