arr是一个字符串数组,但字符串是不可变的——简单地调用toUpperCase()一个字符只会给你一个新的大写字符的引用,而不会改变原始字符串。您需要显式地重新分配数组项:
function titleCase(str) {
let arr = str.toLowerCase().split(" ");
for (let i = 0; i < arr.length; i++) {
arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1);
}
return arr.join(" ");
}
console.log(titleCase("I'm a little tea pot"));
或者,也许更优雅的是,您可以使用正则表达式。下面使用lookbehind,它适用于Chrome、Opera和Node的最新版本;lookbehind 使代码看起来更干净,但并非所有地方都支持它:
const titleCase = str => str.replace(
/(?<=^|\s)\S/g,
firstChar => firstChar.toUpperCase()
);
console.log(titleCase("I'm a little tea pot"));
或者,没有后视:
const titleCase = str => str.replace(
/(\S)(\S*)/g,
(_, firstChar, rest) => firstChar.toUpperCase() + rest
);
console.log(titleCase("I'm a little tea pot"));