如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?

例如:

“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/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

其他回答

const capitalizeName = function (name) { 
    const names = name.split(' '); 
    const namesUpper = [];
    for (const n of names) {  
        namesUpper.push(n.replace(n[0], n[0].toUpperCase()));
    } 
    console.log(namesUpper.join(' '));
 }; 
capitalizeName('the Eiffel Tower')

只是因为这是一个真正的单线,我会包括这个答案. 这是一个基于ES6的交叉线单线。

let setStringName = 'the Eiffel Tower';
setStringName = `${setStringName[0].toUpperCase()}${setStringName.substring(1)}`;
var capitalizeMe = "string not starting with capital"

资本化与substr

var capitalized = capitalizeMe.substr(0, 1).toUpperCase() + capitalizeMe.substr(1);

咖啡文字

ucfirst = (str) -> str.charAt(0).toUpperCase() + str.slice(1)

作为一个严格的原型方法:

String::capitalize = -> @charAt(0).toUpperCase() + @slice(1)
s[0].toUpperCase``+s.substr`1`

let s = 'hello there' console.log( s[0].toUpperCase''+s.substr`1` )