首页 > 解决方案 > 如何将字符串大写?

问题描述

我有这个使用 JavaScript 的字符串:

let str = "my city is beautiful."

我想得到:

"My City Is Beautiful"

我试过这个:

str.charAt(0).toUpperCase() + str.slice(1)

但我得到了:

My city is beautiful

请问你能帮帮我吗?

标签: javascript

解决方案


您可以使用split,mapjoin:

"my city is beautiful"
  .split(" ")
  .map(s => s.charAt(0).toUpperCase() + s.slice(1))
  .join(" ")

推荐阅读