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

例如:

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


当前回答

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

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

其他回答

优雅

const capitalize = ([firstChar, ...rest]) => `${firstChar.toUpperCase()}${rest.join('')}`;

如果我可以稍微改变代码,我发现,如果我通过这个功能运行一条所有条线,什么都不会发生,所以......这里是我的条线。

String.prototype.capitalize = function(){
    return this.toLowerCase().replace( /(^|\s)([a-z])/g , function(m, p1, p2) {
        return p1 + p2.toUpperCase();
    });
}

使用 RamdaJs 的另一种方式,是功能编程方式:

firstCapital(str){
    const fn = p => R.toUpper(R.head(p)) + R.tail(p);
    return fn(str);
}

用多个字在一个字符串:

firstCapitalAllWords(str){
    const fn = p => R.toUpper(R.head(p)) + R.tail(p);
    return R.map(fn,R.split(' ', str)).join(' ');
}

最简单的解决方案是:

let yourSentence = 'it needs first letter upper case';

yourSentence.charAt(0).toUpperCase() + yourSentence.substr(1);

或:

yourSentence.charAt(0).toUpperCase() + yourSentence.slice(1);

或:

yourSentence.substr(0, 1).toUpperCase() + yourSentence.substr(1);

使用此 Node.js 模块, http://stringjs.com/ 包,以资本化您的行:

var S = require('string');
S('jon').capitalize().s; //'Jon'
S('JP').capitalize().s; //'Jp'