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

例如:

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


当前回答

下面有一个函数称为ucfirst((缩写为“上例第一字母”):

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

您可以通过称 ucfirst(“某些链条”)来资本化一个链条 - 例如,

ucfirst("this is a test") --> "This is a test"

在第一行中,它提取第一Letter,然后在第二行中,它通过呼叫第一Letter.toUpperCase()来资本化第一Letter,并将其与其余的行列相结合,这是通过呼叫str.substr(1)来找到的。

你可能认为这会失败一个空的线条,而且实际上在一个语言如C,你会不得不为此加密,但是在JavaScript中,当你采取一个空的线条,你只是得到一个空的线条。

其他回答

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

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

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

"hello, world!".capitalize();

预计产量是:

"Hello, world!"
/*
 * As terse as possible, assuming you're using ES version 6+
 */
var upLetter1=s=>s.replace(/./,m=>m.toUpperCase());

console.log(upLetter1("the quick brown fox jumped over the lazy dog."));
//\\ The quick brown fox jumped over the lazy dog. //\\

创建一行资本的第一字母

第一個解決方案

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

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");

他说:“这是一个测试。

我只会用一个常见的表达式:

myString = '    the quick green alligator...';
myString.trim().replace(/^\w/, (c) => c.toUpperCase());

试试这个代码:

alert("hello".substr(0, 1).toUpperCase() + "hello".substr(1));

它正在采取“你好”中的第一个字符,资本化它,并添加其余的。