Javascript 将第一个单词的第一个字母和无条件大写的数组中的单词大写

Javascript 将第一个单词的第一个字母和无条件大写的数组中的单词大写,javascript,arrays,Javascript,Arrays,这是我试过的代码 函数语句案例(str,非条件资本化){ 让数组=str str=str.toLowerCase().split(“”) console.log(str) //toUpperCase街() unconditionallyCapitalized=unconditionallyCapitalized.join().toLowerCase() console.log(非条件资本化) 对于(var x=1;x来说,这是一个更有用的答案: unconditionallyCapitaliz

这是我试过的代码

函数语句案例(str,非条件资本化){
让数组=str
str=str.toLowerCase().split(“”)
console.log(str)
//toUpperCase街()
unconditionallyCapitalized=unconditionallyCapitalized.join().toLowerCase()
console.log(非条件资本化)

对于(var x=1;x来说,这是一个更有用的答案:
unconditionallyCapitalized.join().toLowerCase()
为您提供了一个字符串
i,moon,shadow
,它不如['i',moon',shadow']数组有用(这是我用
map
函数替换的)

当一个单词有句号时,您只需将其置于console.log-ing中。相反,您可以将其
str[x+1]
之后的单词大写(这将是新句子中的第一个单词)

我用替换了您的拆分/合并/合并序列


最后,您不需要转到
x这里有一个现代的方法。这里的关键是在数组上使用来检查您要大写的单词列表(数组)中的单词是否与您正在迭代的当前单词匹配(通过空格将字符串分解成数组后)

.replace(/\W/g,”)
从word中删除所有非单词字符,这允许
阴影。
匹配
阴影(当然是小写后)

const cleanString=str=>str.replace(/\W/g',).toLowerCase();
常量大写字母CertainWords=(str,words)=>
str
.拆分(“”)
.地图(
word=>
单词。查找(
大写DWORD=>
cleanString(word)==cleanString(大写DWORD)
)
?word.substring(0,1).toUpperCase()+word.substring(1)
:字
)
.加入(“”);
康斯特街=
“我看着暴风雨,如此美丽却又可怕。月亮的脸在阴影中。”;
const unconditionallyCapitalized=['I','Moon','Shadow'];
console.log(
大写某些单词(str,非条件大写)
);
尝试下一个代码:

函数findAndCapitalize(str,arrStr){
设tempStr=大写第一个字母(str);
arrStr.forEach(项目=>{
让index=str.indexOf(item.toLowerCase());
如果(索引!=-1){
设startPart=tempStr.substring(0,索引),
endPart=tempStr.substring(索引+项长度);
tempStr=起始部分+大写首字母(项目)+结束部分;
}
})
返回tempStr;
函数大写字母(str){
设res=str.charAt(0).toUpperCase()+str.substring(1);
返回res;
}
}
let str=“我观看了风暴,如此美丽却又可怕。月亮的脸在阴影中。”;
让无条件资本化=['I'、'Moon'、'Shadow'];

console.log(findAndCapitalize(str,非条件资本化));
当然!所以第一件事是你没有对带句点的单词做任何事情,只是console.logging。第二件事是检查
。包括
数组
['i','moon','shadow']
比字符串
'i,moon,shadow'更容易
。还有!你本来要去
x的,这没有解释。