如何用空字符串解决这个JavaScript标题框问题



我是JavaScript新手,遇到了一些问题:

构造一个名为titleCase的函数,该函数接受一个字符串并为其设置标题大小写。

titleCase("this is an example") // Should return "This Is An Example"
titleCase("test") // Should return "Test"
titleCase("i r cool") // Should return "I R Cool"
titleCase("WHAT HAPPENS HERE") // Should return "What Happens Here"
titleCase("") // Should return ""
titleCase("A") // Should return "A"

这是我尝试过的代码:

const titleCase = function(text) {
text = text.split(' ');
for (let i = 0; i < text.length; i++) {
text[i] = text[i].toLowerCase().split('');
text[i][0] = text[i][0].toUpperCase();
text[i] = text[i].join('');
}
if (text === "") {
return ""
}
return text.join(' ');
}

它通过了除空字符串""测试之外的所有测试。

您需要移动:

if (text === "") {
return ""
} 

到函数的第一行。

这里有一个简单的解决方案:

function titleCase(s){
let r="";
for (let i=0; i<s.length; i++) r+=(i==0 || s[i-1]==" ")?s[i].toUpperCase():s[i].toLowerCase();
return r;
}
console.log(titleCase("helLo tHERE!"));
console.log(titleCase("this is an example")); //should return "This Is An Example"
console.log(titleCase("test")); //should return "Test"
console.log(titleCase("i r cool")); //should return "I R Cool"
console.log(titleCase("WHAT HAPPENS HERE")); //should return "What Happens Here"
console.log(titleCase("")); //should return ""
console.log(titleCase("A")); //should return "A"

您只需要在函数中声明文本为空作为默认值,并在的循环之前添加if (text === "") {条件。因此,如果文本为空,则在执行for循环之前&";。请检查以下片段:

const titleCase = function(text = '') {
if (text === "") {
return ""
}
text = text.split(' ');
for (let i = 0; i < text.length; i++) {
text[i] = text[i].toLowerCase().split('');
text[i][0] = text[i][0].toUpperCase();
text[i] = text[i].join('');
}
return text.join(' ');
}
console.log(titleCase());
console.log(titleCase("Hello"));
console.log(titleCase("Hello World"));

您可以使用这个简单的函数来解决这个问题。

function titleCase(text) {
return text.split(' ').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ')
}

现在让我们把它分解一下。

首先,我使用text.split(' ')。它将句子转换成每个单词的数组。

例如,

"this is an example"变为['this', 'is', 'an', 'example']

其次,我使用map()将每个单词转换为大写。

word.charAt(0).toUpperCase() + word.slice(1)。这是一种将单词转换为大写的简单方法。它变成了:

['this', 'is', 'an', 'example']``` to ```['This', 'Is', 'An', 'Example']

最后,我只是将每个单词加上一个空格:

join(' ')

然后返回CCD_ 11。

不能用[]表示法修改字符。

要替换字符串的第一个字符,请不要执行

str[0] = str[0].toUppercase()

但是

str = "X" + str.substr(1)

您的功能可以是:

function titleCase(str) {
return str.toLowerCase().replace(/(^|s)[a-z]/g, (a)=>a.toUpperCase());
}

此功能将:

  • 全部转换为小写
  • 然后使用正则表达式将空格(s(后面的字母([a-z](或字符串(^(的开头替换为其大写版本

这些console.log行(在text = text.split(' ');之后(应该可以帮助您理解错误:

const titleCase = function(text) {
text = text.split(' ');
console.log(text)
console.log(text.length)
for (let i = 0; i < text.length; i++) {
text[i] = text[i].toLowerCase().split('');
text[i][0] = text[i][0].toUpperCase();
text[i] = text[i].join('');
}

if (text === "") {
return ""
} 
return text.join(' ');
}

最新更新