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

例如:

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


当前回答

使用步枪功能:

const capitalize = string => string[0].toUpperCase() + string.slice(1)

其他回答

下面是最受欢迎的答案的简短版本,通过将线作为序列来处理第一个字母:

function capitalize(s)
{
    return s[0].toUpperCase() + s.slice(1);
}

更新

根据下面的评论,这在 IE 7 或下方不起作用。

更新2:

要避免未定义为空线(参见 @njzk2 下面的评论),您可以检查一个空线:

function capitalize(s)
{
    return s && s[0].toUpperCase() + s.slice(1);
}

是版本

const capitalize = s => s && s[0].toUpperCase() + s.slice(1)

// to always return type string event when s may be falsy other than empty-string
const capitalize = s => (s && s[0].toUpperCase() + s.slice(1)) || ""
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'
var capitalizeMe = "string not starting with capital"

资本化与substr

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

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

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

结果:

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

只是因为你可以,这并不意味着你应该,但是. 它需要 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("");
};