Tianhe Gao

Title Case a Sentence

Basic Algorithm Scripting: Title Case a Sentence | freeCodeCamp.org

我的,没有完成要求

 1function titleCase(str) {
 2  let newStrArr = []
 3  for (let i = 0; i < str.split(' ').length; i++) {
 4    newStrArr.push(
 5      str.split(' ')[i][0].toUpperCase() +
 6        str.split(' ')[i].slice(1).toLowerCase(),
 7    )
 8  }
 9  return newStrArr.join(' ')
10}
11
12console.log(titleCase("I'm a little tea pot"))

加了 .toLowerCase() 可以了。

这样写有些繁琐。

for…in

1function titleCase(str) {
2  const newTitle = str.split(' ')
3  const updatedTitle = []
4  for (let st in newTitle) {
5    updatedTitle[st] =
6      newTitle[st][0].toUpperCase() + newTitle[st].slice(1).toLowerCase()
7  }
8  return updatedTitle.join(' ')
9}

map()

1  function titleCase(str) {
2    return str
3      .toLowerCase()
4      .split(' ')
5      .map((val) => val.replace(val.charAt(0), val.charAt(0).toUpperCase()))
6      .join(' ')
7  }
8
9  titleCase("I'm a little tea pot")

正则表达式

1function titleCase(str) {
2  return str.toLowerCase().replace(/(^|\s)\S/g, (L) => L.toUpperCase())
3}

No notes link to this note

Welcome to tell me your thoughts via "email"
UP