[英]Convert first letter of each word in a string to Uppercase in JavaScript
I can write this code in a simpler way but I want to write it as a function based code. 我可以以更简单的方式编写此代码,但我想将其编写为基于函数的代码。 I am looking to change the starting letter of each word in a string to uppercase.Please help!!
我想将字符串中每个单词的开头字母更改为大写。请帮忙!
function convertuc(str) {
let arr = str.toLowerCase().split(" ");
for (let s of arr){
let arr2 = arr.map(s.charAt(0).toUpperCase() + s.substring(1)).join(" ");
}
return arr2
};
console.log(convertuc("convert the first letter to upper case")); // Test//
What about to use pure CSS? 如何使用纯CSS?
p { text-transform: capitalize; }
<p>this is a simple sentence.</p>
You're almost there. 你快到了。 You don't need a for loop since you're already using
map
(which does the iteration for you and builds a new array by transforming each string in arr
to a new one based on the function provided). 您不需要for循环,因为您已经在使用
map
(它会为您进行迭代,并根据提供的函数将arr
中的每个字符串转换为新的字符串,从而构建一个新的数组)。
function convertuc(str) { let arr = str.toLowerCase().split(" "); let arr2 = arr.map(s => s.charAt(0).toUpperCase() + s.substring(1)).join(" "); return arr2; // note that arr2 is a string now because of .join(" ") }; console.log(convertuc("convert the first letter to upper case"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.