如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
下面是2018 ECMAScript 6+ 解决方案:
const str = 'The Eiffel Tower'; const newStr = `${str[0].toUpperCase()}${str.slice(1)}`; console.log('Original String:', str); // the Eiffel Tower console.log('New String:', newStr); // The Eiffel Tower
其他回答
解決方案 無法閱讀不定義的「charAt」財產
const capitalize = (string) => {
return string ? string.charAt(0).toUpperCase() + string.slice(1) : "";
}
console.log(capitalize("i am a programmer")); // I am a programmer
var a = "this is a test"
console.log(a.replace(/^[a-z]/g, txt => txt.toUpperCase()));
let capitalize = (strPara)=>{
let arr = Array.from(strPara);
arr[0] = arr[0].toUpperCase();
return arr.join("");
}
let str = capitalize("this is a test");
console.log(str);
将所有单词的第一字母分为一个字符串:
function ucFirstAllWords( str )
{
var pieces = str.split(" ");
for ( var i = 0; i < pieces.length; i++ )
{
var j = pieces[i].charAt(0).toUpperCase();
pieces[i] = j + pieces[i].substr(1);
}
return pieces.join(" ");
}
function capitalize(string) {
return string.replace(/^./, Function.call.bind("".toUpperCase));
}