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

例如:

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


当前回答

函数 capitalizeEachWord(str) { return str.replace(/\w\S*/g,函数(txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); }); } document.write(capitalizeEachWord('foo BAR God bAD'));

其他回答

你可以做这样的事情:

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

这将打印

线条

这里是我的尝试,使一个普遍的功能,只有第一字母,或每个字母的第一字母,包括单词分开的单词(如一些第一名在法语)。

默认情况下,该函数仅将第一个字母归功,其余的字母无触。

参数:

lc: 忠于强迫下载的所有字(s): 忠于资本化每一个字

 

if( typeof String.prototype.capitalize !== "function" ) {
    String.prototype.capitalize = function( lc, all ) {
        if( all ) {
            return this.split( " " )
                       .map( currentValue => currentValue.capitalize( lc ), this )
                       .join( " " )
                       .split( "-" )
                       .map( currentValue => currentValue.capitalize( false ), this )
                       .join( "-" );
        } else {
            return lc
            ? this.charAt( 0 ).toUpperCase() + this.slice( 1 ).toLowerCase()
            : this.charAt( 0 ).toUpperCase() + this.slice( 1 );
        }
    }
}

只有CSS

如果转换仅需要在网页上显示:

p::first-letter {
  text-transform: uppercase;
}

尽管被称为“::第一字”,但它适用于第一个字符,即在 %a 字符的情况下,这个选择器将适用于 % 并且作为这样一个不会被资本化。

ES2015 单线

const capitalizeFirstChar = str => str.charAt(0).toUpperCase() + str.substring(1);

注意事项

在我所执行的指标中,在 string.charAt(0) 和 string(0) 之间没有显著的差异。 但是,请注意,该 string(0) 会为一个空的 string 不定义,因此该函数必须重写以使用“string && string(0)”,这与替代品相比是过于垂直的。

与 substring() 和 slice() 之间的比较

差异在今天相当微小(自己进行测试):

21,580,613.15 ops/s ±1.6% for substring(), 21,096,394.34 ops/s ±1.8% (2.24% 缓慢) for slice()。

此分類上一篇

这里是我的版本,我认为它很容易理解和优雅。

var str = "foo bar baz";

// Capitalize
str.split(' ')
    .map(w => w[0].toUpperCase() + w.substr(1).toLowerCase())
    .join(' ')
// Returns "Foo Bar Baz"

// Capitalize the first letter
str.charAt(0).toUpperCase() + str.slice(1)
// Returns "Foo bar baz"

如果您想修改全覆文本,您可能希望修改其他例子如下:

function capitalize (text) {
    return text.charAt(0).toUpperCase() + text.slice(1).toLowerCase();
}

这将确保下列文本进行更改:

TEST => Test
This Is A TeST => This is a test