5 回答

TA貢獻1786條經驗 獲得超11個贊
將它視為類似數組的對象來獲取第一個字符,將其大寫,然后concat將其視為字符串的其余部分:
const str = "hello World!";
const upper = ([c, ...r]) => c.toUpperCase().concat(...r);
console.log(upper(str));

TA貢獻1998條經驗 獲得超6個贊
你可以charAt用來獲得第一個字母:
const string = "stackoverflow is helpful."
const capitalizedString = string.charAt(0).toUpperCase() + string.slice(1)
console.log(capitalizedString)

TA貢獻1887條經驗 獲得超5個贊
你不想使用替換,也不想使用string[0]。相反,使用下面的小方法
const s = 'foo bar baz';
function ucFirst(str) {
return str.substr(0, 1).toUpperCase() + str.substr(1);
}
console.log(ucFirst(s));

TA貢獻1866條經驗 獲得超5個贊
既然你似乎想知道這里有一個詳細的例子:
function FistWordFirstCharcterCapital() {
let text = document.getElementById("TextInput").value;
let firstSpaceIndex = text.indexOf(" ")!=-1 ? text.indexOf(" ")+1:text.length;
let firstWord = text.substr(0, firstSpaceIndex);
let firstWordUpper = firstWord.charAt(0).toUpperCase() + firstWord.slice(1)
document.getElementById("TextInput").value = firstWordUpper + text.substr(firstSpaceIndex);;
}
<textarea autocomplete="off" cols="30" id="TextInput" name="message" rows="10" style="width: 100%;">
</textarea>
<input id="FistWordFirstCharcterCapital" onclick="FistWordFirstCharcterCapital()" style="color: black;" type="button" value="First word first character capital!" />
添加回答
舉報