下面是一个简单的函数,用于大写句子中的第一个单词。
:输入:'JavaSCRipt是最好的‘
输出:'JavaScript是最好的‘
const firstupper = function(str){
const arr = str.split(' ');
const newArr = [];
for(let item of arr){
item = item.toLowerCase();
newArr.push(item.replace(item[0], item[0].toUpperCase()));
}
const newstr = newArr.join(' ');
console.log(newstr);
}
firstupper('javaSCript is THE besT');
P.S . --这段代码很好用
为什么我不能用小写替换大写的第一个字母,比如:newArr.push(item.toLowerCase().replace(item[0], item[0].toUpperCase()));
当我使用此方法编写代码时,它将第一个单词改为小写,反之亦然。
:输入-> 'JAvaScript是最好的‘输出-> 'javascript是最好的’
发布于 2021-09-01 13:53:30
因为这改变了逻辑。在这个版本中,在item
操作中对.push()
的所有读取都是小写的:
item = item.toLowerCase();
newArr.push(item.replace(item[0], item[0].toUpperCase()));
但是在这个版本中,只有第一次使用item
是小写的:
newArr.push(item.toLowerCase().replace(item[0], item[0].toUpperCase()));
对item[0]
的引用仍然使用任何原始的套管。为了使其符合相同的逻辑,您还需要重复情况,并在那里进行更改:
newArr.push(item.toLowerCase().replace(item.toLowerCase()[0], item.toLowerCase()[0].toUpperCase()));
这显然太混乱,不必要地重复操作。因此,首选原来的工作版本。
发布于 2021-09-01 13:54:02
这可能会有帮助
const str = 'JavaSCRipt is The BEST';
//split the above string into an array of strings
//whenever a blank space is encountered
const arr = str.split(" ");
//loop through each element of the array and capitalize the first letter.
for (var i = 0; i < arr.length; i++) {
arr[i] = arr[i].toLowerCase();
arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1);
}
//Join all the elements of the array back into a string
//using a blankspace as a separator
const str2 = arr.join(" ");
console.log(str2);
//Outptut: Javascript Is The Best
https://stackoverflow.com/questions/69015049
复制相似问题