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

例如:

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


当前回答

我知道这是一个古老的问题,有很多答案,但这里是我的快速剪辑。

const capitalize = (str) => str?.split('').map( (e, i) => i === 0 ? e.toUpperCase() : e ).join('')

其他回答

ucfirst函数工作,如果你这样做。

function ucfirst(str) {
    var firstLetter = str.slice(0,1);
    return firstLetter.toUpperCase() + str.substring(1);
}

谢谢JP的解释。

关于TypeScript

  capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
  }

你可以做这样的事情:

mode =  "string";
string = mode.charAt(0).toUpperCase() + mode.substr(1,mode.length).toLowerCase();
console.log(string);

这将打印

线条

我最近在一个项目中需要类似的功能,这就是我如何实施它:

函数 capitlizeFirst(str) { // checks for null, undefined and empty string if (!str) return; return str.match("^[a-z]")? str.charAt(0).toUpperCase() + str.substring(1) : str; } console.log(capitlizeFirst("")); console.log(capitlizeFirst(null)); console.log(capitlizeFirst(undefined)); console.log(capitlizeFirst("hello world")); console.log(capitlizeFirst("/index.html"));

function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

一些其他答案修改 String.prototype(这个答案也被用来),但我会建议反对这一点现在由于可持续性(很难找到函数在哪里被添加到原型,如果另一个代码使用相同的名称 / 一个浏览器添加一个原始函数与相同的名称在未来可能导致冲突)。