function capitalizeFirstLetterWithRegex(string) { return string.replace(/(^\w{1})/, s => s.toUpperCase()); } console.log(capitalizeFirstLetterWithRegex("js")); // 输出: "Js" 方法3:使用扩展运算符和 map javascript function capitalizeFirstLetterWithSpread(string) { return [...string]...
function capitalizeFirstLetter(str) { return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase(); } var str = "hello world"; var capitalizedStr = capitalizeFirstLetter(str); console.log(capitalizedStr); // 输出 "Hello world"
javascript string capitalize letter 答案function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } 其他一些答案修改了String.prototype (这个答案也是如此),但由于可维护性,我现在建议不要这样做(很难找到函数添加到prototype ,如果其他代码使用相同的函数,可能会导致冲突...
JavaScript: Check if First Letter of a String is Upper Case, Capitalizing the First Letter If we found out that the first letter of the string is lower case, and if we want to capitalize it, we can do that using following method: function capitalizeFirstLetter(word) { return word.charAt ...
function arrayIntersection(arr1, arr2) { return arr1.filter(value => arr2.includes(value)); } 6. 查找两个数组的差集 有时,你需要找到两个数组之间的差异。arrayDifference函数接受两个数组作为参数,并返回它们的差集。 function arrayDifference(arr1, arr2) { ...
function capitalizeFirstLetter(sentence) { var trimmedSentence = sentence.trim(); var firstChar = trimmedSentence.charAt(0); var capitalizedFirstChar = firstChar.toUpperCase(); var remainingChars = trimmedSentence.slice(1); return capitalizedFirstChar.concat(remainingChars); } var sentence = "hello...
function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } console.log(capitalizeFirstLetter('foo')); // Foo 其他一些答案修改 String.prototype (这个答案也曾经使用过),但由于可维护性,我现在建议不要这样做(很难找出函数被添加到 prototype 如果其他代码使用...
更新2:避免undefined有关空字符串,可以检查空字符串:function capitalize(s){ return s && s[0...
function capitalizeFirstLetter(str) { //将字符串拆分为单词数组 var words = str.split(" "); //遍历数组,对每个单词的首字母进行操作 for (var i = 0; i < words.length; i++) { //获取当前单词 var word = words[i]; //将当前单词的首字母转换为大写 var capitalizedWord = word.charAt(0)...
You can capitalize the first letter of a string by using the charAt() and slice() methods in JavaScript. function capitalizeFirstLetter(str) { return str.charAt(0).toUpperCase() + str.slice(1); } let myString = "codedamn"; console.log(capitalizeFirstLetter(myString)); // Outputs: Code...