如何使用JavaScript将字符串中每个单词的首字母大写? [英] How to capitalize the first letter of each word in a string using JavaScript?

查看:95
本文介绍了如何使用JavaScript将字符串中每个单词的首字母大写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个函数,该函数将字符串中每个单词的首字母大写(将字符串转换为首字母大写).

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

例如,当输入为"I'm a little tea pot"时,我希望将"I'm A Little Tea Pot"作为输出.但是,该函数返回"i'm a little tea pot".

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".

这是我的代码:

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

推荐答案

您不会再次将更改分配给阵列,因此您的所有努力都是徒劳的.试试这个:

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

这篇关于如何使用JavaScript将字符串中每个单词的首字母大写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆