javascript - 使用 for 循环将每个单词的首字母大写(不能处理间距)

标签 javascript function

我有一个函数,可以将每个单词的首字母大写。我有一个带有 .map 的简洁解决方案;但是,为了练习,我尝试使用 for 循环来解决它。这是我取得的成就:

我创建了一个 for 循环,但它似乎不起作用。

function UpperWithCycle(str) {
  str = str.split(' ');
  let result = '';

  for (let i = 0; i < str.length; i++) {
    result += str[i].substring(0, 1).toUpperCase() + str[i].substring(1).toLowerCase();
  }
  return result;
}

console.log(UpperWithCycle('hello everyone my name is Andrew, how are you doing?'))

所以,我知道我需要在此处的某处添加 join(' '),但我似乎无法弄清楚将其添加到何处以获得单词之间的空格。在我尝试添加它的任何地方,我都会得到“join is not a function”
所以我在这里缺少什么,伙计们?

最佳答案

您可以在除最后一个单词之外的每个单词后添加空格:

function UpperWithCycle(str) {

  str = str.split(' ');
  let result = '';

  for (let i = 0; i < str.length; i++) {
    result += str[i].substring(0, 1).toUpperCase() + str[i].substring(1).toLowerCase();
    result += i < str.length - 1 ? ' ' : '';
  }
  return result;
}

console.log(UpperWithCycle('hello everyone my name is Andrew, how are you doing?'))

关于javascript - 使用 for 循环将每个单词的首字母大写(不能处理间距),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57923450/

相关文章:

javascript - puppeteer 调试 : finding which line is cuzing the error

javascript - 页面切换之间的动画功能

javascript - 我无法使用 .filter() 方法来过滤正确的索引

c++ - 如何在 Windows 窗体中使用单独的 .cpp 文件定义事件函数?

c# - 如何从 C# 程序运行 bat 文件?

c++ - 非模板类中的函数模板

function - 将类型信息放入 Scala 中的空参数方法调用

javascript - 如何使用 JavaScript 编写 NeoVim 插件?

javascript - 使用 jquery 正则表达式对空电子邮件地址进行验证

javascript - 通过将跨度附加到主体来查找宽度