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

例如:

“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”


当前回答

只是因为你可以,这并不意味着你应该,但是. 它需要 ECMAScript 6 因为代码使用序列破坏。

const capitalizeFirstLetter = s => {
  const type = typeof s;
  if (type !== "string") {
    throw new Error(`Expected string, instead received ${type}`);
  }

  const [firstChar, ...remainingChars] = s;

  return [firstChar.toUpperCase(), ...remainingChars].join("");
};

其他回答

下面是更清洁、更美丽的版本。

var str = '';
return str.replace(new RegExp('^'+str[0]+''), str[0].toUpperCase());

结果:

這是一個測試 -> 這是一個測試

创建一行资本的第一字母

第一個解決方案

“这是一个测试” → “这是一个测试”

var word = "this is a test"
word[0].toUpperCase();

他说:“这是一个测试。

第二個解決方案 第一個字的條件資本

“这是一个测试” → “这是一个测试”

function capitalize(str) {

    const word = [];

    for(let char of str.split(' ')){
        word.push(char[0].toUpperCase() + char.slice(1))
    }

    return word.join(' ');

}

 capitalize("this is a test");

他说:“这是一个测试。

var nameP = prompt("please enter your name");
var nameQ = nameP.slice(0,1);
var nameR = nameP.slice(1,100);
nameQ = nameQ.toUpperCase();
nameP = nameQ + nameR;
console.log("Hello! " + nameP);

出口:

Hello! Alex

如果您的项目中有Lodash,请使用UpperFirst

function capitalize(s) {
    // returns the first letter capitalized + the string from index 1 and out aka. the rest of the string
    return s[0].toUpperCase() + s.substr(1);
}


// examples
capitalize('this is a test');
=> 'This is a test'

capitalize('the Eiffel Tower');
=> 'The Eiffel Tower'

capitalize('/index.html');
=> '/index.html'