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

例如:

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


当前回答

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

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 ucFirstAllWords( str )
{
    var pieces = str.split(" ");
    for ( var i = 0; i < pieces.length; i++ )
    {
        var j = pieces[i].charAt(0).toUpperCase();
        pieces[i] = j + pieces[i].substr(1);
    }
    return pieces.join(" ");
}

好吧,所以我是新的JavaScript. 我无法得到上面的为我工作. 所以我开始把它自己。

String name = request.getParameter("name");
name = name.toUpperCase().charAt(0) + name.substring(1);
out.println(name);

在这里,我从一个表格中获取变量(它也手动工作):

String name = "i am a Smartypants...";
name = name.toUpperCase().charAt(0) + name.substring(1);
out.println(name);

出发:“我是聪明的......”;

我一直在试图做同样的事情(即;资本化第一字母在一个字符串,而它是打字)使用jQuery. 我搜索所有通过网页的答案,但我找不到它. 但是我能够得到一个工作周围使用on()函数在jQuery如下:

$("#FirstNameField").on("keydown",function(e){
    var str = $("#FirstNameField").val();
    if(str.substring()===str.substring(0,1)){
        $("#FirstNameField").val(str.substring(0,1).toUpperCase());
    } 
});

这个功能实际上资本化了第一个字母,而数据输入者则不断打字。

功能性方法

const capitalize = ([s, ...tring]) =>
  [s.toUpperCase(), ...tring]
    .join('');

然后你可以

const titleCase = str => 
  str
    .split(' ')
    .map(capitalize)
    .join(' ')

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

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

参数:

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