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

例如:

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


function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

一些其他答案修改 String.prototype(这个答案也被用来),但我会建议反对这一点现在由于可持续性(很难找到函数在哪里被添加到原型,如果另一个代码使用相同的名称 / 一个浏览器添加一个原始函数与相同的名称在未来可能导致冲突)。

下面有一个函数称为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!"

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

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

谢谢JP的解释。

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

使用:

capitalizedString = someString.capitalize();

此分類上一篇: This Is a Text String

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

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

如果你去其中一个 regex 答案,请记住,它们只会与 ASCII 字符一起工作. 所有的 Unicode 字母都不会被打破. XRegExp 图书馆和其 Unicode 插件解决这个问题,如果你想与 regex 保持。

String.prototype.capitalize = function () {
    return this.replace(XRegExp("^\\p{L}"), function ($0) { return $0.toUpperCase(); })
}

考虑到它仍然不涵盖所有可能性(混合字符,见 http://www.regular-expressions.info/unicode.html),似乎更容易使用.charAt(0).toUpperCase() 方法。

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

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

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

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

下面是最受欢迎的答案的简短版本,通过将线作为序列来处理第一个字母:

function capitalize(s)
{
    return s[0].toUpperCase() + s.slice(1);
}

更新

根据下面的评论,这在 IE 7 或下方不起作用。

更新2:

要避免未定义为空线(参见 @njzk2 下面的评论),您可以检查一个空线:

function capitalize(s)
{
    return s && s[0].toUpperCase() + s.slice(1);
}

是版本

const capitalize = s => s && s[0].toUpperCase() + s.slice(1)

// to always return type string event when s may be falsy other than empty-string
const capitalize = s => (s && s[0].toUpperCase() + s.slice(1)) || ""

咖啡文字

ucfirst = (str) -> str.charAt(0).toUpperCase() + str.slice(1)

作为一个严格的原型方法:

String::capitalize = -> @charAt(0).toUpperCase() + @slice(1)

将所有单词的第一字母分为一个字符串:

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

如果您对每个字母的第一字母进行资本化,并且您的 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)

好吧,所以我是新的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);

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

在CSS中:

p::first-letter {
    text-transform:capitalize;
}
// Uppercase first letter
function ucfirst(field) {
    field.value = field.value.substr(0, 1).toUpperCase() + field.value.substr(1);
}

使用:

<input type="text" onKeyup="ucfirst(this)" />

在 CoffeeScript 中,添加一个字符串的原型:

String::capitalize = ->
  @substr(0, 1).toUpperCase() + @substr(1)

使用将是:

"woobie".capitalize()

谁得益:

"Woobie"

一个可能的解决方案:

function ConvertFirstCharacterToUpperCase(text) {
    return text.substr(0, 1).toUpperCase() + text.substr(1);    
}

使用此:

 alert(ConvertFirstCharacterToUpperCase("this is string"));

此分類上一篇: JS Fiddle

yourString.replace(/^[a-z]/, function(m){ return m.toUpperCase() });

(您可以将其嵌入到函数中,或者甚至将其添加到 String 原型中,如果您经常使用它。

我們可以獲得第一個角色與我最喜歡的RegExp之一,看起來像一個可愛的微笑: /^./

String.prototype.capitalize = function () {
  return this.replace(/^./, function (match) {
    return match.toUpperCase();
  });
};

对于所有咖啡豆:

String::capitalize = ->
  @replace /^./, (match) ->
    match.toUpperCase()

...和所有认为有更好的方式做到这一点的男孩,没有扩展原生原型:

var capitalize = function (input) {
  return input.replace(/^./, function (match) {
    return match.toUpperCase();
  });
};

对于另一个案例,我需要它来资本化第一封信,下载其余的案例,下列案例让我改变了这个功能:

//es5
function capitalize(string) {
    return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
capitalize("alfredo")  // => "Alfredo"
capitalize("Alejandro")// => "Alejandro
capitalize("ALBERTO")  // => "Alberto"
capitalize("ArMaNdO")  // => "Armando"

// es6 using destructuring 
const capitalize = ([first,...rest]) => first.toUpperCase() + rest.join('').toLowerCase();

函数有两个论点:

起点 - 起点指数; 长度 - 依据的长度为资本化

String.prototype.subUpper = function () {
    var result = this.toString();
    var start = 0;
    var length = 1;
    if (arguments.length > 0) {
        start = arguments[0];
        if (start < this.length) {
            if (arguments.length > 1) {
                length = arguments[1];
            }
            if (start + length > this.length) {
                length = this.length - start;
            }
            var startRest = start + length;
            var prefix = start > 0 ? this.substr(0, start) : String.empty;
            var sub = this.substr(start, length);
            var suffix = this.substr(startRest, this.length - startRest);
            result = prefix + sub.toUpperCase() + suffix;
        }
    }
    return result;
};
String.prototype.capitalize = function(allWords) {
   return (allWords) ? // If all words
      this.split(' ').map(word => word.capitalize()).join(' ') : // Break down the phrase to words and then recursive
                                                                 // calls until capitalizing all words
      this.charAt(0).toUpperCase() + this.slice(1); // If allWords is undefined, capitalize only the first word,
                                                    // meaning the first character of the whole string
}

然后:

 "capitalize just the first word".capitalize(); ==> "Capitalize just the first word"
 "capitalize all words".capitalize(true); ==> "Capitalize All Words"

更新2016年11月(ES6),只是为了乐趣:

const capitalize = (string = '') => [...string].map(    // Convert to array with each item is a char of
                                                        // string by using spread operator (...)
    (char, index) => index ? char : char.toUpperCase()  // Index true means not equal 0, so (!index) is
                                                        // the first character which is capitalized by
                                                        // the `toUpperCase()` method
 ).join('')                                             // Return back to string

此分類上一篇: 你好(Hello)

我一直在试图做同样的事情(即;资本化第一字母在一个字符串,而它是打字)使用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());
    } 
});

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

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

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

参数:

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

或者你可以使用Sugar.js资本()

例子:

'hello'.capitalize()           -> 'Hello'
'hello kitty'.capitalize()     -> 'Hello kitty'
'hello kitty'.capitalize(true) -> 'Hello Kitty'
var str = "test string";
str = str.substring(0,1).toUpperCase() + str.substring(1);

如果您使用 Underscore.js 或 Lodash, underscore.string 图书馆提供链接扩展,包括资本化:

_.capitalize(string) 将序列的第一字母转换为顶端。

例子:

_.capitalize("foo bar") == "Foo bar"

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

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 capitalizeMe(str, force){
    str = force ? str.toLowerCase() : str;
    return str.replace(/(\b)([a-zA-Z])/g,
        function(firstLetter){
            return firstLetter.toUpperCase();
        });
}


var firstName = capitalizeMe($firstName.val());

使用:

var str = “ruby java”; console.log(str.charAt(0).toUpperCase() + str.substring(1));

它将输出“Ruby java”到控制台。

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

var S = require('string');
S('jon').capitalize().s; //'Jon'
S('JP').capitalize().s; //'Jp'
var capitalizeMe = "string not starting with capital"

资本化与substr

var capitalized = capitalizeMe.substr(0, 1).toUpperCase() + capitalizeMe.substr(1);

我在我的开发环境中使用这些线路,特别是当我与HTTP等API合作时:

假设您有一个 HTTP 标题,您希望在其名义中资本化每个初始字母,并在其组成词之间添加混合物。

'access control allow origin'
    .replace(/\b\w/g, function (match) {
        return match.toUpperCase();
    })
    .split(' ')
    .join('-');

// Output: 'Access-Control-Allow-Origin'

这可能不是最优雅和最有吸引力的功能定义,但它肯定会完成工作。

function capitalize(string) {
    return string.replace(/^./, Function.call.bind("".toUpperCase));
}

目前投票的答案是正确的,但它不会在资本化第一个字符之前切断或检查链条的长度。

String.prototype.ucfirst = function(notrim) {
    s = notrim ? this : this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');
    return s.length > 0 ? s.charAt(0).toUpperCase() + s.slice(1) : s;
}

设置 notrim 论点,以防止第一条线被推翻:

'pizza'.ucfirst()         => 'Pizza'
'   pizza'.ucfirst()      => 'Pizza'
'   pizza'.ucfirst(true)  => '   pizza'

发表一个编辑 @salim 的答案,包括本地字母转换。

var str = "test string";
str = str.substring(0,1).toLocaleUpperCase() + str.substring(1);

如果你想在一行中资本化每个第一封信,例如Hello to the world,你可以使用以下(由史蒂夫·哈里森重复):

function capitalizeEveryFirstLetter(string) {
    var splitStr = string.split(' ')
    var fullStr = '';

    $.each(splitStr,function(index){
        var currentSplit = splitStr[index].charAt(0).toUpperCase() + splitStr[index].slice(1);
        fullStr += currentSplit + " "
    });

    return fullStr;
}

您可以通过使用以下方式呼叫:

capitalizeFirstLetter("hello to the world");
function capitalize(s) {
    // returns the first letter capitalized + the string from index 1 and out aka. the rest of the string
    return s[0].toUpperCase() + s.substr(1);
}


// examples
capitalize('this is a test');
=> 'This is a test'

capitalize('the Eiffel Tower');
=> 'The Eiffel Tower'

capitalize('/index.html');
=> '/index.html'

看看这个解决方案:

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

如同它:

function capitalize(string,a) {
    var tempstr = string.toLowerCase();
    if (a == false || a == undefined)
        return tempstr.replace(tempstr[0], tempstr[0].toUpperCase());
    else {
        return tempstr.split(" ").map(function (i) { return i[0].toUpperCase() + i.substring(1) }).join(" ");
    }
}


capitalize('stack overflow yeah!',true)); //Stack Overflow Yeah!

capitalize('stack stack stack stack overflow yeah!'));//Stack overflow yeah!

https://jsfiddle.net/dgmLgv7b/

如果您对发布的几种不同的方法的性能感兴趣:

以下是基于此JSperf测试的最快方法(从最快到最慢的订单)。

正如你可以看到的那样,前两种方法在性能方面基本上是相似的,而改变 String.prototype 则在性能方面是最慢的。

// 10,889,187 operations/sec
function capitalizeFirstLetter(string) {
    return string[0].toUpperCase() + string.slice(1);
}

// 10,875,535 operations/sec
function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

// 4,632,536 operations/sec
function capitalizeFirstLetter(string) {
    return string.replace(/^./, string[0].toUpperCase());
}

// 1,977,828 operations/sec
String.prototype.capitalizeFirstLetter = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

此分類上一篇

如果您已经(或正在考虑)使用Lodash,解决方案很容易:

_.upperFirst('fred');
// => 'Fred'

_.upperFirst('FRED');
// => 'FRED'

_.capitalize('fred') //=> 'Fred'

查看他们的文档: https://lodash.com/docs#capitalize

_.camelCase(“Foo Bar”); //=>“FooBar”

https://lodash.com/docs/4.15.0#camelCase

_.lowerFirst('Fred');
// => 'fred'

_.lowerFirst('FRED');
// => 'fRED'

_.snakeCase('Foo Bar');
// => 'foo_bar'

Vanilla JavaScript for first up 案例:

function upperCaseFirst(str){
    return str.charAt(0).toUpperCase() + str.substring(1);
}

一条线路:

此分類上一篇: 重定向,重定向,重定向,重定向,重定向

这就是同样的行动:

var newStr = string.slice(0,1).toUpperCase() + string.slice(1);

这将容忍可能领先的白空间,并不会错过一条线中的第一字母的目标,因此,它可能会改善已经在线上可用的好解决方案。

str = "   the Eifel Tower";
str.replace(/\w/, str.match(/\w/)[0].toUpperCase());
>> "   The Eifel Tower";

但是,如果对白条行进行执行,则会导致“软”错误,为了避免这种可能的错误或对白条行或数字进行不必要的处理,可以使用温和的条件警卫:

+str!=+str ?  str.replace(/\w/, str.match(/\w/)[0].toUpperCase()) : str;

首先,我只是想清楚资本化在这个背景下意味着什么,“这条线是资本化”可靠的来源

你可以从例子中看到,只要这不是OP正在寻找的东西,它应该说的是“我如何制作一条线的第一字”(不资本化线)

function ucfirst (str) {
    return typeof str != "undefined" ? (str += '', str[0].toUpperCase() + str.substr(1)) : '';
}

解释

typeof str != "undefined" // Is str set
? // true
str += '' // Turns the string variable into a string
str[0].toUpperCase() // Get the first character and make it upper case
+ // Add
str.substr(1) // String starting from the index 1 (starts at 0)
: // false
''; // Returns an empty string

这将与任何论点或没有论点工作。

undefined         === ""
""                === ""
"my string"       === "My string"
null              === "Null"
undefined         === "";
false             === "False"
0                 === "0"
true              === "True"
[]                === ""
[true,0,"",false] === "True,0,,false"

为了仅仅资本化第一封信,并将其余的字符串下载案例:

function capitalize(str) {
     var splittedEnter = str.split(" ");
     var capitalized;
     var capitalizedResult;
     for (var i = 0 ; i < splittedEnter.length ; i++){
         capitalized = splittedEnter[i].charAt(0).toUpperCase();
         splittedEnter[i] = capitalized + splittedEnter[i].substr(1).toLowerCase();
    }
    return splittedEnter.join(" ");
}

capitalize("tHiS wiLL be alL CapiTaLiZED.");

结果将是:

这一切都将被资本化。

函数 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'));

var capitalized = yourstring[0].toUpperCase() + yourstring.substr(1);

一个小改进 - 每个字在标题。

String.prototype.toTitleCase = function(){
    return this.replace(/\b(\w+)/g, function(m,p){ return p[0].toUpperCase() + p.substr(1).toLowerCase() });
}

var s = 'heLLo, wOrLD!';
console.log(s.toTitleCase()); // Hello, World!

如果您的项目中有Lodash,请使用UpperFirst

function cap(input) {
    return input.replace(/[\.\r\n\t\:\;\?\!]\W*(\w)/g, function(match, capture) {
         // For other sentences in the text
         return match.toUpperCase();
    }).replace(/^\W*\w/, function(match, capture) {
        // For the first sentence in the text
        return match.toUpperCase();
    });;
}

var a = "hi, dear user. it is a simple test. see you later!\r\nbye";
console.log(cap(a));
// Output: Hi, dear user. It is a simple test. See you later!
// Bye

使用原型

String.prototype.capitalize = function () {
    return this.charAt(0) + this.slice(1).toLowerCase();
  }

或使用功能

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

只有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()。

此分類上一篇

总是更好地处理这些类型的东西使用CSS首先,一般来说,如果你可以用CSS解决一些事情,先去,然后尝试JavaScript解决你的问题,所以在这种情况下尝试使用CSS的第一字母,并应用文本转换:资本化;

所以,试着为此创建一个类,这样你就可以在全球范围内使用它,例如:.first-letter-uppercase 并在你的 CSS 中添加下面的类似内容:

.first-letter-uppercase:first-letter {
    text-transform:capitalize;
}

另一个选项是JavaScript,所以最好的会是这样的东西:

function capitalizeTxt(txt) {
  return txt.charAt(0).toUpperCase() + txt.slice(1); //or if you want lowercase the rest txt.slice(1).toLowerCase();
}

把它称为:

capitalizeTxt('this is a test'); // return 'This is a test'
capitalizeTxt('the Eiffel Tower'); // return 'The Eiffel Tower'
capitalizeTxt('/index.html');  // return '/index.html'
capitalizeTxt('alireza');  // return 'Alireza'
capitalizeTxt('dezfoolian');  // return 'Dezfoolian'

如果你想重复使用它一次又一次,最好将其添加到JavaScript Native String,所以如下:

String.prototype.capitalizeTxt = String.prototype.capitalizeTxt || function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

把它称为下面的:

'this is a test'.capitalizeTxt(); // return 'This is a test'
'the Eiffel Tower'.capitalizeTxt(); // return 'The Eiffel Tower'
'/index.html'.capitalizeTxt();  // return '/index.html'
'alireza'.capitalizeTxt();  // return 'Alireza'

适用于所有 Unicode 字符的解决方案

57 81 不同答案这个问题,一些离主题,但其中没有一个提出重要问题,没有一个列出的解决方案将与亚洲字符, emoji,和其他高 Unicode 点值字符在许多浏览器工作。

const consistantCapitalizeFirstLetter = "\uD852\uDF62".length === 1 ?
    function(S) {
        "use-strict"; // Hooray! The browser uses UTF-32!
        return S.charAt(0).toUpperCase() + S.substring(1);
    } : function(S) {
        "use-strict";
        // The browser is using UCS16 to store UTF-16
        var code = S.charCodeAt(0)|0;
        return (
          code >= 0xD800 && code <= 0xDBFF ? // Detect surrogate pair
            S.slice(0,2).toUpperCase() + S.substring(2) :
            S.charAt(0).toUpperCase() + S.substring(1)
        );
    };
const prettyCapitalizeFirstLetter = "\uD852\uDF62".length === 1 ?
    function(S) {
        "use-strict"; // Hooray! The browser uses UTF-32!
        return S.charAt(0).toLocaleUpperCase() + S.substring(1);
    } : function(S) {
        "use-strict";
        // The browser is using UCS16 to store UTF-16
        var code = S.charCodeAt(0)|0;
        return (
          code >= 0xD800 && code <= 0xDBFF ? // Detect surrogate pair
            S.slice(0,2).toLocaleUpperCase() + S.substring(2) :
            S.charAt(0).toLocaleUpperCase() + S.substring(1)
        );
    };

请注意,上述解决方案试图计算 UTF-32. 然而,规格正式表示,浏览器必须在 UTF-16 地图中完成一切。 然而,如果我们都聚集在一起,做我们的部分,并开始为 UTF32 做好准备,那么 TC39 可能会允许浏览器开始使用 UTF-32 (就像 Python 如何使用 24 位字符的每个字符一样)

这个解决方案可能是新的,也许是最简单的。

函数第一UpperCase(输入) {返回输入[0].toUpperCase() + input.substr(1); } console.log(第一UpperCase(“资本化第一字母”));

试试这个代码:

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

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

使用 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(' ');
}

只是因为你可以,这并不意味着你应该,但是. 它需要 ECMAScript 6 因为代码使用序列破坏。

const capitalizeFirstLetter = s => {
  const type = typeof s;
  if (type !== "string") {
    throw new Error(`Expected string, instead received ${type}`);
  }

  const [firstChar, ...remainingChars] = s;

  return [firstChar.toUpperCase(), ...remainingChars].join("");
};

你可以这样做,这样一行。

string[0].toUpperCase() + string.substring(1)

一条线(“输入线可以设置到任何条线”):

inputString.replace(/.{1}/, inputString.charAt(0).toUpperCase())
var a = "this is a test"
console.log(a.replace(/^[a-z]/g, txt => txt.toUpperCase()));

下面是2018 ECMAScript 6+ 解决方案:

const str = 'The Eiffel Tower'; const newStr = `${str[0].toUpperCase()}${str.slice(1)}`; console.log('Original String:', str); // the Eiffel Tower console.log('New String:', newStr); // The Eiffel Tower

下面是更清洁、更美丽的版本。

var str = '';
return str.replace(new RegExp('^'+str[0]+''), str[0].toUpperCase());

结果:

這是一個測試 -> 這是一個測試

这是一个简单的

const upper = lower.replace(/^\w/, c => c.toUpperCase());

你可以做这样的事情:

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

这将打印

线条

yourString.replace(/\w/, c => c.toUpperCase())

我发现这支箭的功能是最容易的。 替换符合你的字符的第一个字符(\w)字符,并将其转换为顶端。

创建一行资本的第一字母

第一個解決方案

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

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

他说:“这是一个测试。

s[0].toUpperCase``+s.substr`1`

let s = 'hello there' console.log( s[0].toUpperCase''+s.substr`1` )

功能性方法

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

然后你可以

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

最短的 3 个解决方案, 1 和 2 处理 s 行是 “”, null 和 undefined 的情况:

 s&&s[0].toUpperCase()+s.slice(1)        // 32 char

 s&&s.replace(/./,s[0].toUpperCase())    // 36 char - using regexp

'foo'.replace(/./,x=>x.toUpperCase())    // 31 char - direct on string, ES6

s=‘foo bar’; console.log( s&&s[0].toUpperCase()+s.slice(1) ); console.log( s&s.replace(/./,s[0].toUpperCase()); console.log( 'foo bar'.replace(/./,x=>x.toUpperCase()) );

有一个非常简单的方式来实现它通过替代。

'foo'.replace(/^./, str => str.toUpperCase())

结果:

'Foo'

关于TypeScript

  capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
  }

有几种方法可以做到这一点,请尝试下面的

var lower = 'the Eiffel Tower';
var upper = lower.charAt(0).toUpperCase() + lower.substr(1);

如果你很舒服的常规表达,你会这样做:

var upper = lower.replace(/^\w/, function (chr) {
  return chr.toUpperCase();
});

你甚至可以通过使用更现代化的合成来迈出一步:

const upper = lower.replace(/^\w/, c => c.toUpperCase());

此外,这也将照顾如示例中提到的负面场景,如从特殊字符开始的单词,如!@#$%^&*()}{{[];':",<>/?。

我更喜欢使用一个以功能方式为导向的解决方案(例如地图序列):

Array.from(str).map((letter, i) => i === 0 ? letter.toUpperCase() : letter ).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);

好吧,所有答案都会崩溃,如果方法通过一些意想不到的数据类型,如对象或功能。

因此,要确保它不会在任何情况下崩溃,我们将需要检查类型。

首頁 〉外文書 〉文學 〉文學 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉

string = string.replace(string.charAt(0), string.charAt(0).toUpperCase());

该方法将采取一个值,然后将其分成一系列的线条。

const firstLetterToUpperCase = value => {
 return value.replace(
    value.split("")["0"], // Split stirng and get the first letter 
    value
        .split("")
        ["0"].toString()
        .toUpperCase() // Split string and get the first letter to replace it with an uppercase value
  );
};
/*
 * 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. //\\

使用 JS 取代字符串方法 & 一个常见的表达 w/ 一个词界限似乎很简单。

首頁 〉外文書 〉文學 〉西洋文學 〉Capitalize the first words' first character: "the Eiffel Tower" --> "The Eiffel Tower"

str.replace(/\b\w/, v => v.toUpperCase())

首頁 〉外文書 〉文學 〉西洋文學 〉Capitalize all words' first character: "the Eiffel Tower" --> "The Eiffel Tower"

str.replace(/\b\w/g, v => v.toUpperCase())

首頁 〉外文書 〉文學 〉文學 〉Capitalize First Word: Shortest

text.replace(/(^.)/, m => m.toUpperCase())

每一个字:最短

text.replace(/(^\w|\s\w)/g, m => m.toUpperCase());

如果你想确保剩下的在底部:

text.replace(/(^\w|\s\w)(\S*)/g, (_,m1,m2) => m1.toUpperCase()+m2.toLowerCase())

我们将使用CSS来实现这一点,它也可以从外部CSS设置。

<span text-transform="capitalize ">The first letter of each word becomes an upper case</span>

使用Vanilla JavaScript,我们可以:

let string = "test case"

string = string[0].toUpperCase() + string.substring(1)
//return "Test case"

此分類上一篇:</b/>

字符串[0].toUpperCase():将字符串中的第一个字符转换为顶部字符串

string.substring(1):在行中删除第一个字母并返回剩余的字符

text-transform="capitalize":在这个标签的顶部字母中创建每个字母的第一个字母. 如果您使用“uppercase”作为文本转换的值,标签中的每个字母将是一个字母。

任何类型的字符串都可以转换 -

此分類上一篇: Yourstring

var str = yOuRsTrING.toLowerCase(); // Output: yourstring
str.charAt(0).toUpperCase() + str.slice(1); // Output: Y + ourstring = Yourstring

只是因为这是一个真正的单线,我会包括这个答案. 这是一个基于ES6的交叉线单线。

let setStringName = 'the Eiffel Tower';
setStringName = `${setStringName[0].toUpperCase()}${setStringName.substring(1)}`;

每个链条的第一个字符都被资本化了。

函数资本化(词){返回词[0].toUpperCase() + word.slice(1).toLowerCase(); } console.log(capitalize(“john”)); //John console.log(capitalize(“BRAVO”)); //Bravo console.log(capitalize(“BLAne”)); //Blane

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

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

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

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"

尝试下列功能:

function capitalize (string) {
  return [].map.call(string, (char, i) => i ? char : char.toUpperCase()).join('')
}

使用:

capitalize('hello, world!')

结果:

Hello, world!

已经有这么多好答案,但你也可以使用一个简单的CSS转换:

text-transform: capitalize;

div.text-capitalize { 文本转型:资本化; } <h2>文本转型:资本化:</h2> <div class="text-capitalize">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>

您可以使用下面的常规表达式:

return string1.toLowerCase().replace(/^[a-zA-z]|\s(.)/ig, L => L.toUpperCase());

你可以做 str.replace(str[0], str[0].toUpperCase())。

看看这个例子:

let str = “Hello, WORLD!” let newStr = str.replace(str[0], str[0].toUpperCase()) console.log(“str:”, str) console.log(“newStr:”, newStr)

安装和加载Lodash:

import { capitalize } from "lodash";

capitalize('test') // Test

使用步枪功能:

const capitalize = string => string[0].toUpperCase() + string.slice(1)

第一封信与验证的资本化

function capitalizeFirstLetter(str) {
    return (str && typeof str === 'string') ? (str.charAt(0).toUpperCase() + str.slice(1)) : "";
}

测试

console.log(capitalizeFirstLetter(0)); // Output: ""
console.log(capitalizeFirstLetter(null)); // Output: ""
console.log(capitalizeFirstLetter("test")); // Output: "Test"
console.log(capitalizeFirstLetter({})); // Output: ""

下面是我所使用的功能:

capitalCase(text: string = 'NA') {
    return text
      .trim()
      .toLowerCase()
      .replace(/\w\S*/g, (w) => w.replace(/^\w/, (c) => c.toUpperCase()));
  }

console.log('this cApitalize TEXt');
const capitalizeName = function (name) { 
    const names = name.split(' '); 
    const namesUpper = [];
    for (const n of names) {  
        namesUpper.push(n.replace(n[0], n[0].toUpperCase()));
    } 
    console.log(namesUpper.join(' '));
 }; 
capitalizeName('the Eiffel Tower')

优雅

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

你应该这样做:

let text = "lower case";
text = text.charAt(0).toUpperCase() + text.substring(1, text.length);

我知道这是一个古老的问题,有很多答案,但这里是我的快速剪辑。

const capitalize = (str) => str?.split('').map( (e, i) => i === 0 ? e.toUpperCase() : e ).join('')

当我们说资本时,这意味着每个字中的第一个字母应该在上方,而成功的字符则在下方。

第一個函數下有兩個函數,第一個函數將使一條字符的第一個字符在上方,成功的字符在下方,第二個函數將使一條字符在標題字符,這意味著每個字符的第一個字符將在頭部。

// Will make will first letter of a sentence or word uppercase function capital(word){ word = word.toLowerCase() return word[0].toUpperCase() + word.substring(1); } // Will make first letter in each word capital function titleCase(title) { title = title.toLowerCase(); const words = title.split(' '); const titleCaseWords = words.map(word) => word[0].toUpperCase() + word.substring(

我尝试了不同的方法。

function myFun(val) {
 var combain='';
  for (let i = 0; i < val.length; i++) {
     combain  +=  val[i].charAt(0).toUpperCase() + val[i].substring(1, val[i].length)+'-';
  }
  return  combain.replaceAll('-',' ');
}
var str = 'sreehari_bsn_alli'.replaceAll('_', ' ');
str = str.split(' ');

let op = myFun(str);

console.log(op ) 和

此代码还将在链条的开始和结束时处理额外的空间。

讓 val ='這是測試'; val = val.trim(); val = val.charAt(0).toUpperCase() + val.slice(1); console.log("Value => ", val);

带有箭功能

let fLCapital = s => s.replace(/./, c => c.toUpperCase())
fLCapital('this is a test') // "This is a test"

用火箭功能,另一种解决方案

let fLCapital = s => s = s.charAt(0).toUpperCase() + s.slice(1);
fLCapital('this is a test') // "This is a test"

与 Array 和 地图()

let namesCapital = names => names.map(name => name.replace(/./, c => c.toUpperCase()))
namesCapital(['james', 'robert', 'mary']) // ["James", "Robert", "Mary"]

您可以使用 regex 方法:

str.replace(/(^|\s)\S/g, letter => letter.toUpperCase());

将所有单词的第一字母分为一个字符串:

function capitalize(str) {
  return str.split(' ').map(word => word.charAt(0).toUpperCase() + word.toLowerCase().slice(1)).join(' ');
}

資本化和無資本化第一條線。

功能包括:

/** First Character uppercase */
function capitalize(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
}

/** First Character lowercase */
function uncapitalize(str) {
    return str.charAt(0).toLowerCase() + str.slice(1);
}

例1“第一个字符上方”:

alert(capitalize("hello world"));

标签:Hello World

示例2“第一字符下载案例”:

alert(uncapitalize("Hello World, today is sunny"));

此分類上一篇: Hello World, Today Is Sunny

我最近在一个项目中需要类似的功能,这就是我如何实施它:

函数 capitlizeFirst(str) { // checks for null, undefined and empty string if (!str) return; return str.match("^[a-z]")? str.charAt(0).toUpperCase() + str.substring(1) : str; } console.log(capitlizeFirst("")); console.log(capitlizeFirst(null)); console.log(capitlizeFirst(undefined)); console.log(capitlizeFirst("hello world")); console.log(capitlizeFirst("/index.html"));

我需要做一个完整的名字资本化,如阿米尔·迪亚菲(Amir Diafi),所以我分裂了链条,以获得这些名字的序列,并资本化了每个字母的第一字母。

const value = 'amir diafi karim mohammed' const splited_names = value.split(' ') let capitalizedValue = '' for (const iterator of splited_names) { capitalizedValue += ` ${iterator.charAt(0).toUpperCase()}${iterator.slice(1)}` } capitalizedValue.trim() console.log(capitalizedValue) //amir diafi karim => Amir Diafi Karim

如果你想在一个字符串中资本化每一个字,你可以使用以下字符串:

'all_lowercase Capitalized lower_then_Upper a'.replace(/(?<=\b)[a-z](?=\w*)/g, c => c.toUpperCase())
// prints "All_lowercase Capitalized Lower_then_Upper A"

此分類上一篇: I like this one:

yourString.replace(/(^[a-z])/i, (str, firstLetter) => firstLetter.toUpperCase())
var nameP = prompt("please enter your name");
var nameQ = nameP.slice(0,1);
var nameR = nameP.slice(1,100);
nameQ = nameQ.toUpperCase();
nameP = nameQ + nameR;
console.log("Hello! " + nameP);

出口:

Hello! Alex

一个简单的,紧凑的功能,将完成你的工作:

const capitalize = str => str.split(' ').map(sub => sub.charAt(0).toUpperCase() + sub.slice(1)).join(' ');

“Foo” > “Foo” “Foo Bar” > “Foo Bar”

这个代码在某些情况下可能工作得很好:

函数 capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } console.log(capitalizeFirstLetter('foo')); // Foo // 但如果我们有这样的它不会工作好 console.log(capitalizeFirstLetter('fOo')); // FOo

但是,如果你真的想确保,只有第一个字母被资本化,其余的字母是由下层字母构成的,你可以调整代码如下:

函数 capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase(); } console.log(capitalizeFirstLetter('fOo')); // Foo

解決方案 無法閱讀不定義的「charAt」財產

const capitalize = (string) => {
        return string ? string.charAt(0).toUpperCase() + string.slice(1) : "";
    }

console.log(capitalize("i am a programmer")); // I am a programmer

这样做的一个简单的方式是:

如果您想将其添加到 String.prototype:

好吧,这里是一个更简单的方法,空间线和这一切。

首先,你應該知道,一條線是一系列字符。

这个答案应该在所有空间线上工作。

假设你的字符串在一个变量 yourString:

const yourString = "el salvacion sucks" const capitalizeString = yourString.split(" ").长度 > 0? yourString.split(" ").map((item) => 项目[0].toUpperCase() + 项目.substring(1)).join(" ") : yourString[0].toUpperCase() + yourString.substring(1) console.log(capitalizeString)

点击 Run Code Snippet 按钮查看结果

简单的ES6合成与模板链

const capitalize = (str) => { return `${str[0].toUpperCase()}${str.slice(1)}` // return str[0].toUpperCase() + str.slice(1) // without template string } console.log(capitalize(“这是一个测试”)); console.log(capitalize(“埃菲尔塔”)); console.log(capitalize(“/index.html”)); /* “这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/inde”

您可以使用 String#chatAt 获取第一个字符,将其转向上方,然后将其与链条的剩余部分相结合。

function capitalizeFirstLetter(v) {
  return v.charAt(0).toUpperCase() + v.substring(1);
}
let capitalize = (strPara)=>{
    let arr = Array.from(strPara);
    arr[0] = arr[0].toUpperCase();
    return arr.join("");
}

let str = capitalize("this is a test");
console.log(str);

使用 Tailwind CSS

<p class="capitalize">The quick brown fox</p>

此分類上一篇: Quick Brown Fox

(src: https://tailwindcss.com/docs/text-transform#transforming-text)

在这里,单行代码存档字母第一字母资本使用JS

yourstring?.charAt(0)?.toUpperCase() + yourstring?.slice(1).toLocaleLowerCase()