我想将给定的字符串转换为标题大小写:
const titleCase = function (text) {
if (text === "") return "";
let textArr = text.split(" ");
const outputArr = textArr.map(
ele => ele.toLowerCase().replace(ele[0], ele[0].toUpperCase())
);
const output = outputArr.join(" ");
return output;
};
const test1 = titleCase("this is an example");
const test2 = titleCase("WHAT HAPPENS HERE");
console.log(test1);
console.log(test2);
test1
给了我正确的结果This Is An Example
,但test2返回what happens here
,这不是我想要的结果。
我很困惑。。。哪里出了问题?
当您在test2
字符串上运行它时,映射函数中的每个ele
都是大写单词。当您试图替换函数中的ele[0]
时,它会在没有大写字母的字符串中查找大写字符。即用"WHAT"替换字符串what
中的W
ele[0]
。尝试:
ele => ele.toLowerCase().replace(ele[0].toLowerCase(), ele[0].toUpperCase())
您可以将字符串转换为lowerCase,然后使代码更可读:
const titleCase = string => string
.toLowerCase()
.split(' ')
.map(i => i.charAt(0).toUpperCase() + i.slice(1))
.join(' ')
或es5:
function titleCase(string) {
return string
.toLowerCase()
.split(" ")
.map(function (i) {
return i.charAt(0).toUpperCase() + i.slice(1);
})
.join(" ");
}