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

例如:

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


当前回答

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

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

谢谢JP的解释。

其他回答

如果你需要所有的字母,从一个字母开始,你可以使用以下函数:

const capitalLetters = (s) => {
    return s.trim().split(" ").map(i => i[0].toUpperCase() + i.substr(1)).reduce((ac, i) => `${ac} ${i}`);
}

例子:

console.log(`result: ${capitalLetters("this is a test")}`)
// Result: "This Is A Test"

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

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

谢谢JP的解释。

看看这个解决方案:

var stringVal = 'master';
stringVal.replace(/^./, stringVal[0].toUpperCase()); // Returns Master

如果您对每个字母的第一字母进行资本化,并且您的 usecase 在 HTML 中,您可以使用以下 CSS:

<style type="text/css">
    p.capitalize {text-transform:capitalize;}
</style>
<p class="capitalize">This is some text.</p>

此分類上一篇: CSS Text-Transform Property(W3Schools)

下面是更以对象为导向的方法:

Object.defineProperty(String.prototype, 'capitalize', {
  value: function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
  },
  enumerable: false
});

你会称之为这个功能,如下:

"hello, world!".capitalize();

预计产量是:

"Hello, world!"