如何在JavaScript中创建字符串大写的第一个字母?

时间:2009-06-22 08:25:32

标签: javascript string letter capitalize

如何将字符串的第一个字母设为大写,但不更改任何其他字母的大小写?

例如:

  • "this is a test" - > "This is a test"
  • "the Eiffel Tower" - > "The Eiffel Tower"
  • "/index.html" - > "/index.html"

108 个答案:

答案 0 :(得分:5279)

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

其他一些答案修改String.prototype(这个答案也是如此),但由于可维护性,我现在建议不要这样做(很难找到函数添加到prototype的位置和如果其他代码使用相同的名称/浏览器将来添加具有相同名称的本机函数,则可能导致冲突。

答案 1 :(得分:1273)

这是一种更加面向对象的方法:

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

你可以这样调用这个函数:

"hello world".capitalize();

预期输出为:

"Hello world" 

答案 2 :(得分:481)

在CSS中:

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

答案 3 :(得分:259)

以下是流行答案的缩短版本,通过将字符串视为数组来获取第一个字母:

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

<强>更新

根据以下评论,这在IE 7或更低版​​本中不起作用。

更新2:

为避免undefined为空字符串(请参阅@njzk2's comment below),您可以检查空字符串:

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

答案 4 :(得分:162)

以下是最佳解决方案:

第一个解决方案在CSS中:

strings[parameter]

第二个解决方案

p {
  text-transform: capitalize;
}

您也可以将其添加到function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase(); } ,以便您可以使用其他方法将其链接:

String.prototype

并像这样使用它:

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

第三个解决方案

'string'.capitalizeFirstLetter() // String

答案 5 :(得分:156)

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

以下是基于this jsperf test的最快方法(从最快到最慢排序)。

正如您所看到的,前两种方法在性能方面基本相当,而改变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);
}

enter image description here

答案 6 :(得分:141)

对于另一个案例,我需要它来大写第一个字母和小写其余部分。以下情况让我改变了这个功能:

//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();

答案 7 :(得分:63)

var string = "hello world";
string = string.charAt(0).toUpperCase() + string.slice(1);
alert(string);

答案 8 :(得分:63)

这是2018年的ES6 +解决方案

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

答案 9 :(得分:60)

将字符串中所有单词的首字母大写:

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

答案 10 :(得分:51)

如果您已经(或考虑)使用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'

香草js的第一个大写:

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

答案 11 :(得分:46)

我们可以用我最喜欢的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();
  });
};

答案 12 :(得分:46)

String.prototype.capitalize = function(allWords) {
   return (allWords) ? // if all words
      this.split(' ').map(word => word.capitalize()).join(' ') : //break down phrase to words then  recursive calls until capitalizing all words
      this.charAt(0).toUpperCase() + this.slice(1); // if allWords is undefined , capitalize only the first word , mean the first char 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 char which is capitalized by `toUpperCase()` method
 ).join('')                                             //return back to string

然后capitalize("hello") // Hello

答案 13 :(得分:44)

如果您使用underscore.jsLo-Dash,则underscore.string库会提供字符串扩展名,包括大写字母:

  

_。capitalize(string)将字符串的第一个字母转换为   大写。

示例:

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

答案 14 :(得分:39)

仅限CSS

p::first-letter {
  text-transform: uppercase;
}
  • 尽管被称为::first-letter,但它适用于第一个字符,即在字符串%a的情况下,此选择器将应用于%,因此a不会被大写。
  • 在IE9 +或IE5.5 +中,只有一个冒号(:first-letter)支持遗留表示法。

ES2015单线

由于有很多答案,但在ES2015中没有能够有效解决原始问题的答案,我想出了以下内容:

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

说明

  • parameters => function被称为arrow function
  • 我使用名称capitalizeFirstChar代替capitalizeFirstLetter,因为OP没有要求代码将整个字符串中的第一个字母大写,而是第一个字母(如果它是字母,当然)。
  • const使我们能够将capitalizeFirstChar声明为常量,这是理想的,因为作为程序员,您应该始终明确说明您的意图。
  • 在我执行的基准测试中,string.charAt(0)string[0]之间没有显着差异。但请注意,对于空字符串,string[0]将为undefined,因此应将其重写为string && string[0],与替代方案相比,这样做过于冗长。
  • string.substring(1)string.slice(1)快。

基准

  • 此解决方案为4,956,962 ops / s±3.03%,
  • 4,577,946 ops / s±1.2%获得最多投票答案。
  • 在Google Chrome 57上使用JSBench.me创建。

Solutions' comparison

答案 15 :(得分:38)

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

答案 16 :(得分:37)

CSS似乎更容易:

<style type="text/css">
    p.capitalize {text-transform:capitalize;}
</style>
<p class="capitalize">This is some text.</p>

这是来自 CSS text-transform Property W3Schools)。

答案 17 :(得分:37)

使用 CSS优先处理这些内容总是更好,一般来说,如果你可以使用CSS解决问题,那么首先去做,然后尝试JavaScript来解决你的问题,所以在这种情况下,请尝试在CSS中使用:first-letter并应用text-transform:capitalize;

因此,请尝试为其创建一个类,以便全局使用它,例如:.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'

如果你想一遍又一遍地重复使用它,最好将它附加到javascript原生字符串,如下所示:

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'

答案 18 :(得分:36)

如果您想重新格式化全文字幕文本,您可能希望修改其他示例:

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

这将确保更改以下文本:

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

答案 19 :(得分:34)

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'

答案 20 :(得分:30)

这是一个名为 ucfirst()的函数(“大写首字母”的缩写):

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

您可以通过调用 ucfirst(“some string”)来大写字符串 - 例如,

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

它的工作原理是将字符串分成两部分。在第一行它拉出 firstLetter 然后在第二行它通过调用 firstLetter.toUpperCase()来大写 firstLetter 并将其与字符串的其余部分,通过调用 str.substr(1)找到。

你可能会认为这对于一个空字符串会失败,实际上在像C这样的语言中你必须要满足这个要求。但是在JavaScript中,当你获取一个空字符串的子字符串时,你只需返回一个空字符串。

答案 21 :(得分:28)

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

用法:

capitalizedString = someString.capitalize();

这是一个文字字符串=&gt;这是一个文本字符串

答案 22 :(得分:27)

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

答案 23 :(得分:23)

有一种非常简单的方法可以通过替换来实现。对于ES6:

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

结果:

'Foo'

答案 24 :(得分:21)

查看此解决方案:

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

答案 25 :(得分:20)

仅因为这确实是一个班轮,所以我将包括此答案。这是一个基于ES6的内插字符串一衬。

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

答案 26 :(得分:19)

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

(您可以将其封装在函数中,如果经常使用它,甚至可以将其添加到String原型中。)

答案 27 :(得分:17)

ucfirst功能可以正常工作。

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

感谢J-P的批评。

答案 28 :(得分:16)

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

我发现此箭头功能最简单。 Replace与字符串的第一个字母字符(\w)匹配,并将其转换为大写。不需要任何爱好者。

答案 29 :(得分:15)

你可以像这样一行

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

答案 30 :(得分:14)

一种实用的方法

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

那么你可以

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

答案 31 :(得分:14)

每个字符串的第一个字符大写。

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


console.log(capitalize("john")); //John
console.log(capitalize("BRAVO")); //Bravo
console.log(capitalize("BLAne")); //Blane

答案 32 :(得分:14)

上面已经有很多好的答案,但是您也可以使用简单的CSS

text-transform: capitalize;

div.c {
  text-transform: capitalize;
}
<h2>text-transform: capitalize:</h2>
<div class="c">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>

答案 33 :(得分:13)

CoffeeScript中,添加原型以获取字符串:

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

用法是:

"woobie".capitalize()

哪个收益率:

"Woobie"

答案 34 :(得分:13)

var str = "ruby java";

alert(str.charAt(0).toUpperCase() + str.substring(1));

它将返回"Ruby java"

http://jsfiddle.net/amitpandya/908c8e2v/

result link in jsfiddle

答案 35 :(得分:12)

// Uppercase first letter
function ucfirst(field) {
    field.value = field.value.substr(0, 1).toUpperCase() + field.value.substr(1);
}

用法:

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

答案 36 :(得分:12)

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

答案 37 :(得分:12)

发布@ salim答案的编辑,以包含区域设置字母转换。

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

答案 38 :(得分:10)

CoffeeScript

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

作为String原型方法:

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

答案 39 :(得分:10)

一种可能的解决方案:

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

使用此:

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

这是有效的JS Fiddle

答案 40 :(得分:10)

使用原型

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

或使用功能

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

答案 41 :(得分:10)

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

&#13;
&#13;
function firstUpperCase(input)
{
    return input[0].toUpperCase()+input.substr(1);
}

console.log(firstUpperCase("capitalize first letter"));
&#13;
&#13;
&#13;

答案 42 :(得分:10)

最短:当s字符串为""nullundefined时,3种解决方案,1和2处理情况:

 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',我们得到

'Foo bar'

答案 43 :(得分:10)

在现有答案中,我没有看到与星形飞机代码点或国际化有关的问题。使用给定脚本,“大写”在每种语言中并不意味着相同。

最初,我没有看到任何与星体平面代码点相关的问题的答案。在那里is one,但是有点埋没了(我想是这样的!)


大多数建议的功能如下:

function capitalizeFirstLetter(str) {
  return str[0].toUpperCase() + str.slice(1);
}

但是,某些大小写的字符不在BMP(基本多语言平面,代码点U + 0至U + FFFF)之外。例如,使用以下Deseret文本:

capitalizeFirstLetter(""); // ""

此处的第一个字符不能大写,因为字符串的数组索引属性无法访问字符或代码点。他们访问UTF-16代码单元。切片时也是如此,索引值指向代码单位。

碰巧UTF-16代码单位在两个范围(U + 0到U + D7FF和U + E000到U + FFFF)的代码点是1:1。大多数大小写字符都属于这两个范围,但并非全部。

从ES2015开始,处理此问题变得容易一些。 String.prototype[@@iterator]产生对应于代码点*的字符串。因此,例如,我们可以这样做:

function capitalizeFirstLetter([ first, ...rest ]) {
  return [ first.toUpperCase(), ...rest ].join('');
}

capitalizeFirstLetter("") // ""

对于更长的字符串,这可能效率不高** –我们真的不需要迭代其余部分。我们可以使用String.prototype.codePointAt来获取第一个(可能的)字母,但是我们仍然需要确定切片应从何处开始。避免迭代其余部分的一种方法是测试第一个代码点是否在BMP之外。如果不是,则切片从1开始,如果是,则切片从2开始。

function capitalizeFirstLetter(str) {
  const firstCP = str.codePointAt(0);
  const index = firstCP > 0xFFFF ? 2 : 1;

  return String.fromCodePoint(firstCP).toUpperCase() + str.slice(index);
}

capitalizeFirstLetter("") // ""

我们也可以在ES5及以下版本中通过在必要时进一步采用该逻辑来使其工作。 ES5中没有用于处理代码点的内在方法,因此我们必须手动测试第一个代码单元是否为代理***:

function capitalizeFirstLetter(str) {
  var firstCodeUnit = str[0];

  if (firstCodeUnit < '\uD800' || firstCodeUnit > '\uDFFF') {
    return str[0].toUpperCase() + str.slice(1);
  }

  return str.slice(0, 2).toUpperCase() + str.slice(2);
}

capitalizeFirstLetter("") // ""

在一开始,我还提到了国际化的考虑。其中一些非常难以解释,因为它们不仅需要使用什么语言的知识,而且还需要使用该语言单词的特定知识。例如,爱尔兰语字母“ mb”在单词开头大写为“ mB”,而德国eszett从未以单词开头(afaik),这意味着从德语中的“ SS”小写需要附加知识(可能是“ ss”,也可以是“ß”,具体取决于单词)。

此问题最著名的例子可能是土耳其语。在土耳其拉丁语中,i的大写形式为İ,而I的小写形式为ı(它们是两个不同的字母)。幸运的是,我们确实有办法解决这个问题:

function capitalizeFirstLetter([ first, ...rest ], locale) {
  return [ first.toLocaleUpperCase(locale), ...rest ].join('');
}

capitalizeFirstLetter("italya", "en") // "Italya"
capitalizeFirstLetter("italya", "tr") // "İtalya"

在浏览器中,用户最喜欢的语言标记由navigator.language表示,在navigator.languages处找到了优先顺序的列表,并且可以使用{{ 1}}。


极有可能,提出这个问题的人不会担心Deseret的大小写或国际化。但是,最好注意这些问题,因为即使当前不关心这些问题,您也很有可能最终会遇到它们。它们不是“边缘”情况,或更确切地说,它们不是按定义边缘情况-在整个国家/地区,大多数人还是会说土耳其语,并且将代码单元与代码点相结合是相当合理的。错误的常见来源(尤其是表情符号)。字符串和语言都非常复杂!


*或代理代码单位(如果孤立的话)

**也许。我还没测试过除非您确定大写是一个有意义的瓶颈,否则我可能不会大惊小怪-选择您认为最清晰易读的任何内容。

***这样的功能可能希望同时测试第一个和第二个代码单元,而不仅仅是第一个,因为第一个单元可能是孤立的代理。例如,输入“ \ uD800x”将按原样将X大写。

答案 44 :(得分:9)

或者您可以使用Sugar.js capitalize()

示例:

'hello'.capitalize()           -> 'Hello'
'hello kitty'.capitalize()     -> 'Hello kitty'
'hello kitty'.capitalize(true) -> 'Hello Kitty'

答案 45 :(得分:9)

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

var str = "foo bar baz";

//capitalize
str.split(" ").map(function(i){return i[0].toUpperCase() + i.substring(1)}).join(" ");
//return "Foo Bar Baz"

//capitalize first letter
str.charAt(0).toUpperCase() + str.slice(1)
//return "Foo bar baz"

答案 46 :(得分:9)

a.slice(0,1).toUpperCase()+a.slice(1)

let a = 'hello',
    fix = a.slice(0,1).toUpperCase()+a.slice(1)
    
console.log(fix)

答案 47 :(得分:9)

可以通过多种方法尝试以下操作

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

这还将解决一些负面情况,例如示例中以!@#$%^&*()}{{[];':",.<>/?之类的特殊字符开头的单词。

答案 48 :(得分:9)

使用箭头功能:

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

答案 49 :(得分:8)

如果您使用其中一个正则表达式的答案,请记住它们只能使用ASCII字符。你所有的unicode字母都不会大写。如果你想坚持使用正则表达式,XRegExp库及其unicode插件可以解决这个问题。所以这样的事情会起作用:

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()方法似乎更容易。

答案 50 :(得分:8)

仅用大写第一个字母并将其余的字符串小写:

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

结果将是:

  

这将全部资本化。

答案 51 :(得分:7)

这是我尝试制作一个通用函数,它只能使第一个字母或每个单词的第一个字母大写,包括用短划线分隔的单词(就像法语中的一些名字一样)。

默认情况下,该功能仅使首字母大写,而其余部分保持不变。

<强>参数

lc true 以小写字母的其余部分 所有 true 以大写每个单词

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

答案 52 :(得分:7)

var capitalizeMe = "string not starting with capital"

使用substr

进行大写
var capitalized = capitalizeMe.substr(0, 1).toUpperCase() + capitalizeMe.substr(1);

答案 53 :(得分:7)

我只用正则表达式

#include "library.h"

答案 54 :(得分:7)

优雅

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

答案 55 :(得分:6)

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

输出:“我是Smartypants ......”;

答案 56 :(得分:6)

喜欢它:

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/

答案 57 :(得分:6)

单行:

'string'.replace(/(^[a-z])/,function (p) { return p.toUpperCase(); } )

答案 58 :(得分:6)

一个小改进 - 标题词中的每一个字。

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

答案 59 :(得分:6)

57 这个问题的81个不同的答案,一些偏离主题,但没有一个提出重要的问题,列出的所有解决方案都不适用于亚洲字符,表情符号和其他高unicode许多浏览器中的点值字符。这是一个解决方案:

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

请注意,上述解决方案会尝试考虑UTF32。但是,该规范正式声明浏览器需要以UTF16映射到UCS2中的所有内容。尽管如此,如果我们都聚在一起,做好我们的准备并开始为UTF32做准备,那么TC39可能会允许浏览器开始使用UTF32(就像Python如何为字符串的每个字符使用24位)。对于一位说英语的人来说,这似乎是愚蠢的:没有人只使用latin-1曾经不得不处理Mojibake,因为所有字符编码都支持Latin-I。但是,其他国家(如中国,日本,印度尼西亚等)的用户并不是那么幸运。他们不仅在网页上,而且从Javascript中经常处理编码问题:许多中文/日文字符被Javascript视为两个字母,因此可能在中间分开,导致 和 (两个问号)这对最终用户毫无意义)。如果我们可以开始为UTF32做好准备,那么TC39可能只允许浏览器执行Python多年前所做的事情,这使Python在处理高unicode字符方面非常受欢迎:使用UTF32。

consistantCapitalizeFirstLetterIE3+中正常运行。 prettyCapitalizeFirstLetter需要IE5.5 +(请参阅this document的第250页顶部)。然而,这些事实更像是笑话,因为很可能你的网页上的其余代码甚至无法在IE8中运行 - 因为这些旧版浏览器中存在所有DOM和JScript错误以及缺少功能。此外,没有人再使用IE3或IE5.5。

答案 60 :(得分:6)

我们将使用CSS实现此目的。 NB 也可以从外部CSS设置

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

还使用香草JavaScript,我们可以做到:

let string = "test case"

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

//console.log(string) "Test case"

说明:
string [0] .toUpperCase():将字符串中的第一个字母转换为大写字母

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

text-transform =“大写:将此标签中每个单词的首字母大写,如果您使用“ uppercase”作为text-transform的值,则标签中的每个字母均为大写字母

答案 61 :(得分:5)

首先,我只想澄清大写在这种情况下的意义。  “ T 他的 S tring s C apitalized”Reliable source

您可以从提供的示例中看到,这不是OP正在寻找的内容。它应该说的是“如何使字符串大写的第一个字母”(不大写字符串

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

解释

typeof str !="undefined" // is str set
? // true 
str += '' // turn 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 
''; //return empty string

这将适用于任何参数或根本没有参数。

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

答案 62 :(得分:5)

function capitalizeEachWord(str) {
    return str.replace(/\w\S*/g, function(txt) {
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });
}

document.write(capitalizeEachWord('foo BAR God bAD'));

答案 63 :(得分:5)

这个很简单

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

答案 64 :(得分:5)

最简单的解决方案是:

import { fakeAuth } from './path-to-auth-js-file';

或:

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

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

或:

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

答案 65 :(得分:4)

我一直在尝试使用jQuery做同样的事情(即在键入时将字符串中的第一个字母大写)。我在网上搜索了答案,但找不到它。但是我能够在jQuery中使用on()函数来解决这个问题:

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

当数据输入者连续输入时,此函数实际上将第一个字母大写。

答案 66 :(得分:4)

这做同样的动作:

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

答案 67 :(得分:4)

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

YoUrStRiNg-> Yourstring

private void DataResult(string result, string acc, string file)
{
    lock (this)
    {
        if (result == "good")
        {
            MetroTextBox metroTextBox = this.textBox1;
            metroTextBox.Text = string.Join(metroTextBox.Lines.Distinct(), acc, Environment.NewLine);
            file = Path.Combine(this.papka, "good.txt");
            if (!Directory.Exists(this.papka))
            {
                Directory.CreateDirectory(this.papka);
            }
            File.AppendAllText(file, acc + "\r\n");
            Listing.good++;
        }
        if (result == "error")
        {
            Listing.error++;
        }
    }
}

答案 68 :(得分:3)

如果项目中有Lodash,请使用upperFirst

答案 69 :(得分:3)

function cap(input) {
    return input.replace(/[\.\r\n\t\:\;\?\!]\W*(\w)/g, function(match, capture) {
                  // for other sentences in text
                  return match.toUpperCase();
                 }).replace(/^\W*\w/, function(match, capture) {
                 // for first sentence in 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

答案 70 :(得分:3)

使用RamdaJs的Anotehr方式,函数式编程方式

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

答案 71 :(得分:3)

这是一个漂亮而清洁的版本;

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

结果:

这是一个测试 - &gt;这是一个测试

答案 72 :(得分:3)

Unicode和区域设置感知

使用当前语言功能:

function capitalize([firstLetter, ...rest]) {
  return [firstLetter.toLocaleUpperCase(), ...rest].join('');
}

console.log(capitalize('foo bar'));
console.log(capitalize('ѷҥӕ'))
console.log(capitalize('?❄??⭐'));

// Title Case
console.log(
  'Title Case:',
  'foo bar'
    .split(/\s+/)
    .map(capitalize)
    .join(' '),
);

我们接受destructured字符串作为唯一的参数[firstLetter, ...rest],将第一个字符分配给变量firstLetter并获得其余字符的数组(...rest )绑定到rest变量。例如。对于字符串lorem ipsum,它应类似于:

capitalize('lorem ipsum');
// firstLetter = 'l'
// rest = ['o', 'r', 'e', 'm', ' ', 'i', 'p', 's', 'u', 'm'];

现在,我们需要做的就是使用firstLetter.toLocaleUpperCase()将第一个字母spread operator的大写版本添加到rest数组中,并使用{将结果数组连接成字符串{3}}

答案 73 :(得分:3)

您可以执行"currentDate":new Date("Asia/Kolkata")

检查此示例:

str.replace(str[0], str[0].toUpperCase())

答案 74 :(得分:3)

只需安装并加载lodash

import { capitalize } from "lodash";

capitalize('test') // Test

答案 75 :(得分:3)

你应该这样做:

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

答案 76 :(得分:2)

该函数有两个参数: start - 起始索引; length - 大写字母的子串长度

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

答案 77 :(得分:2)

这是我虔诚地使用的:

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

答案 78 :(得分:2)

使用NodeJS http://stringjs.com/包的这个模块来大写你的String

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

答案 79 :(得分:2)

在使用HTTP之类的API时,我在开发环境esp中使用了这些内容:

假设您有一个HTTP标题,您希望将其名称中的每个首字母大写,并在其组成单词之间添加连字符,您可以使用此基本和&amp;简单的例程:

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

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

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

答案 80 :(得分:2)

当前投票的答案是正确的,但在大写第一个字符之前,不会修剪或检查字符串的长度。

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'

答案 81 :(得分:2)

这个会容忍可能的前导空格,并且不会错过字符串中第一个字母的目标。因此,它可能会改善线程上已有的良好解决方案。

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;

答案 82 :(得分:2)

试试这段代码:

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

它正在做的是将hello中的第一个字符大写并将其余部分添加到其中。

答案 83 :(得分:2)

为了彻底,添加另一种我没有看到提到的方式。只因为你可以,但并不意味着你应该这样做。需要ES6,因为代码使用数组解构。

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

答案 84 :(得分:2)

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

答案 85 :(得分:2)

我更喜欢使用面向功能方式的解决方案(例如映射数组):

Array.from(str).map((letter, i) => i === 0 ? letter.toUpperCase() : letter ).join('');

答案 86 :(得分:2)

如果您需要所有单词都以大写字母开头,则可以使用下一个功能:

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"

答案 87 :(得分:1)

如果您要将字符串中的每个首字母大写,例如MainViewController变为hello to the world,您可以使用以下内容(从Steve Harrison转发):

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

答案 88 :(得分:1)

一个班轮(&#34; inputString可以设置为任何字符串&#34;) inputString.replace(/.{1}/ ,inputString.charAt(0).toUpperCase())

答案 89 :(得分:1)

您可以执行以下操作:

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

这将打印

String

答案 90 :(得分:1)

对于TypeScript

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

答案 91 :(得分:1)

好吧,如果该方法传递了某些意外类型的数据,例如Objectfunction,则所有答案都会崩溃。

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

capitalizeFirstLetter = string => {
  if (typeof string == "string") {
      console.log("passed");
    return string.charAt(0).toUpperCase() + string.slice(1);
  } else {
    console.log("error");
    return string;
  }
};

//type function
console.log(
  capitalizeFirstLetter(() => {
    return true;
  })
);
// error
//  () => { return true; }

//type object
console.log(capitalizeFirstLetter({ x: 1 }));
// error
// Object { x: 1 }

//type boolean
console.log(capitalizeFirstLetter(true));
// error
// true

//type undefined
console.log(capitalizeFirstLetter(undefined));
// error
// undefined

//type null
console.log(capitalizeFirstLetter(null));
// error
// null

//type NaN
console.log(capitalizeFirstLetter(NaN));
// error
// NaN

//type number
console.log(capitalizeFirstLetter(2));
// error
// 2

//type any for e.g. class
class Jaydeep {}
console.log(capitalizeFirstLetter(new Jaydeep()));
// error
// Object {}

//type string
console.log(capitalizeFirstLetter("1"));
console.log(capitalizeFirstLetter("a"));
console.log(capitalizeFirstLetter("@"));
console.log(capitalizeFirstLetter(""));
// 1
// A
// @
//  :empty string

答案 92 :(得分:1)

/**
 * As terse as possible, assuming you're using ES version 6+
 */
const upLetter1=s=>s.replace(/^[a-z]/,m=>m.toUpperCase());

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

答案 93 :(得分:1)

首字母大写:最短

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())

答案 94 :(得分:1)

尝试使用以下功能:

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

用法:

capitalize('hello world')

结果:

Hello world

答案 95 :(得分:1)

通过验证将首字母大写

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

测试

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

答案 96 :(得分:1)

这是我使用的函数:

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

console.log('this cApitalize TEXt');

答案 97 :(得分:1)

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')

答案 98 :(得分:0)

  

制作首字母大写字母

     

第一个解决方案

“这是测试”->“这是测试”

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

它将给出=>“这是测试”

答案 99 :(得分:0)

该方法将获取一个值,然后将其拆分为一个字符串数组。

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

答案 100 :(得分:0)

您可以使用RegEXP作为波纹管:

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

答案 101 :(得分:0)

您可以使用RegEXP解决它:

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

答案 102 :(得分:0)

我知道这是一个有很多答案的老问题,但这是我的简短摘要。

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

答案 103 :(得分:0)

我尝试了不同的方法

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

答案 104 :(得分:-1)

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

答案 105 :(得分:-1)

当我们说大写时,意思是每个单词的第一个字母应该是大写的,后面的字符是小写的。

下面有两个函数,第一个函数将字符串的第一个字母转为大写,后面的为小写。第二个函数将一个字符串变成标题大小写,这意味着每个单词中的每个第一个字母都将大写

// 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 words capital

function titleCase(title) {
  title = title.toLowerCase();
  const words = title.split(' ');
  const titleCaseWords = words.map((word) => word[0].toUpperCase() + word.substring(1));
  return titleCaseWords.join(' ');
}

const title = titleCase('the QUICK brown fox') 
const caps = capital('the QUICK brown fox') 

console.log(title); // The Quick Brown Fox
console.log(caps); // The quick brown fox

答案 106 :(得分:-2)

容易腻:

//确定同意所以这里是编辑后的版本我不能简单地超越这个

function FirstUpperCase(inputString){
  return inputString.replace(inputString[0],inputString[0].toUpperCase());
};

输入:你好学生 输出:你好学生

答案 107 :(得分:-7)

如果我可以改变一下代码。我发现如果我通过这个函数运行全部大写字符串,则没有任何反应。所以...这是我的tid位。首先强制字符串小写。

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