[英]upperCase the first element of a string in JavaScript
The error shows " AssertionError: expected ' NEVER GIVE UP' to deeply equal ' NEVER GIVE UP ' " and I can't figure out why blank in the beginning of a string is ignored.错误显示“ AssertionError: expected ' NEVER GIVE UP' to deep equal ' NEVER GIVE UP ' “我不明白为什么忽略字符串开头的空白。 Here is my code:
这是我的代码:
function letterCapitalize(str) {
if (str === '') {
return ''
}
let string = '' //array to string
let word = str.split(' ')
for (let i = 0; i < word.length; i++) {
if (word[i] !== '') {
string = string + word[i][0].toUpperCase() + word[i].slice(1, word[i].length) + ' '
} else if (word[i] === '') {
string = ' ' + string
}
}
return string.slice(0, string.length - 1)
}
The console log examples include:控制台日志示例包括:
let output1 = letterCapitalize('hello world');
console.log(output1); // "Hello World"
let output2 = letterCapitalize('javascript is sexy ');
console.log(output2); // "Javascript Is Sexy "
Your test seems to want a space at the end, try this if you really want to capitalize the string, or share your test case code so I can have a look.您的测试似乎需要一个空格,如果您真的想将字符串大写,请尝试此操作,或者分享您的测试用例代码以便我查看。
const capitalize = str => {
if (!str) return "";
return str
.split(" ")
.map(el => el[0].toUpperCase() + el.slice(1))
.join(" ");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.