我如何在JavaScript中使string大写的第一个字母?
如何使string的第一个字母大写,但不改变任何其他字母的情况?
例如:
-  "this is a test"– >"This is a test"
-   "the Eiffel Tower"– >"The Eiffel Tower"
-   "/index.html"– >"/index.html"
另一个scheme
 function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } 
 一些其他的答案修改String.prototype (这个答案也用于),但我会build议现在由于可维护性(很难找出函数被添加到prototype并可能导致冲突,如果其他代码使用相同的名称/浏览器将来会添加一个具有相同名称的本地函数)。 
更加面向对象的方法:
 String.prototype.capitalize = function() { return this.charAt(0).toUpperCase() + this.slice(1); } 
接着:
 "hello world".capitalize(); => "Hello world" 
在CSS中:
 p:first-letter { text-transform:capitalize; } 
下面是一个stream行答案的缩写版本,通过将string视为数组来获取第一个字母:
 function capitalize(s) { return s[0].toUpperCase() + s.slice(1); } 
更新:
根据下面的评论,这不适用于IE 7或以下。
更新2:
 为了避免undefined空string(请参阅下面的@njzk2的注释 ),可以检查一个空string: 
 function capitalize(s) { return s && s[0].toUpperCase() + s.slice(1); } 
对于另一种情况,我需要它的首字母大写,其余的小写。 以下情况使我改变了这个function:
 //es5 function capitalize(string) { return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase(); } capitalise("alfredo") // => "Alfredo" capitalise("Alejandro")// => "Alejandro capitalise("ALBERTO") // => "Alberto" capitalise("ArMaNdO") // => "Armando" // es6 using destructuring const capitalize = ([first,...rest]) => first.toUpperCase() + rest.join('').toLowerCase(); 
如果您对以下几种不同方法的performance感兴趣:
这里是基于这个jsperftesting的最快方法(从最快到最慢)。
 正如你所看到的,前两种方法在性能上基本上是可比的,而改变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); } 
  
 
这是最好的解决scheme:
CSS中的第一个解决scheme
 p:first-letter { text-transform:capitalize; } 
解决scheme二
 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 
第三个scheme :
 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).toLowerCase(); } return pieces.join(" "); } 
 var string = "hello world"; string = string.charAt(0).toUpperCase() + string.slice(1); alert(string); 
大写string中所有单词的首字母:
 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(" "); } 
 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),仅适用于FUN:
 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 
 我们可以用我最喜欢的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(); }); }; 
如果使用underscore.js或Lo-Dash ,则underscore.string库提供string扩展,包括大写:
_.capitalize(string)将string的第一个字母转换为大写。
例:
 _.capitalize("foo bar") == "Foo bar" 
在CSS中似乎更容易:
 <style type="text/css"> p.capitalize {text-transform:capitalize;} </style> <p class="capitalize">This is some text.</p> 
这是从CSS文本转换属性 (在W3Schools )。
 如果您已经(或正在考虑)使用lodash ,则解决scheme非常简单: 
 _.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); } 
 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 capitalized = yourstring[0].toUpperCase() + yourstring.substr(1); 
如果您想要重新格式化全部大写的文本,则可能需要修改其他示例,如下所示:
 function capitalize (text) { return text.charAt(0).toUpperCase() + text.slice(1).toLowerCase(); } 
这将确保以下文本被更改:
 TEST => Test This Is A TeST => This is a test 
 String.prototype.capitalize = function(){ return this.replace( /(^|\s)([az])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } ); }; 
用法:
 capitalizedString = someString.capitalize(); 
这是一个文本string=>这是一个文本string
 var str = "test string"; str = str.substring(0,1).toUpperCase() + str.substring(1); 
仅限CSS
 p::first-letter { text-transform: uppercase; } 
-  尽pipe被称为::first-letter,它适用于第一个字符 ,即在string%a情况下,这个select器将适用于%,因此不会被大写。
-  在IE9 +或IE5.5 +中,只有一个冒号( :first-letter),它在传统表示法中受支持。
ES2015单线
由于有很多答案,但ES2015中没有一个可以有效解决原有问题,所以我提出了以下几点:
 const capitalizeFirstChar = str => str.charAt(0).toUpperCase() + str.substring(1); 
备注
-   parameters => function就是所谓的箭头function 。
-  我使用名称capitalizeFirstChar而不是capitalizeFirstLetter,因为OP没有要求在整个string中首字母大写的代码,而是第一个字符(如果是字母,当然)。
-   const使我们能够将capitalizeFirstChar声明为常量,因为作为程序员,您应该始终明确地陈述您的意图。
-  在我执行的基准testing中, string.charAt(0)和string[0]之间没有显着差异。 但是请注意,string[0]对于空string是undefined的,所以它应该被重写为string && string[0],这与方法相比太冗长了。
-   string.substring(1)比string.slice(1)快。
基准
- 4,956,962 ops / s±3.03%这个解决scheme,
- 最多投票答案为4,577,946 ops / s±1.2%。
- 使用Google Chrome 57上的JSBench.me创build。
  
 
这是一个叫做ucfirst() (简写为“大写的第一个字母”)的函数:
 function ucfirst(str) { var firstLetter = str.substr(0, 1); return firstLetter.toUpperCase() + str.substr(1); } 
你可以通过调用ucfirst(“some string”)来使string大写 – 例如,
 ucfirst("this is a test") --> "This is a test" 
它通过将string分成两部分来工作。 在第一行中,首先取出firstLetter ,然后在第二行中通过调用firstLetter.toUpperCase()来将firstLetter大写,并将其与通过调用str.substr (1)find的string的其余部分进行连接。
你可能会认为这会失败的空string,并且确实在一个像C语言,你将不得不迎合这一点。 但是,在JavaScript中,当你取一个空string的子string时,你只需要返回一个空string。
结帐这个解决scheme:
 var stringVal = 'master'; stringVal.replace(/^./, stringVal[0].toUpperCase()); // returns Master 
 yourString.replace(/^[az]/, function(m){ return m.toUpperCase() }); 
(你可以把它封装在一个函数中,如果你经常使用的话,甚至可以把它添加到String原型中。)
 如果你这样做, ucfirst函数可以工作。 
 function ucfirst(str) { var firstLetter = str.slice(0,1); return firstLetter.toUpperCase() + str.substring(1); } 
感谢JP的鼓舞。
在CoffeeScript中 ,添加到string的原型:
 String::capitalize = -> @substr(0, 1).toUpperCase() + @substr(1) 
用法是:
 "woobie".capitalize() 
这产生:
 "Woobie" 
 // Uppercase first letter function ucfirst(field) { field.value = field.value.substr(0, 1).toUpperCase() + field.value.substr(1); } 
用法:
 <input type="text" onKeyup="ucfirst(this)" /> 
 一般来说,如果你能用CSS解决某些问题,首先要去解决这个问题,然后用JavaScript来解决你的问题,那么最好用CSS来处理这些东西,所以在这种情况下,可以尝试使用CSS中的:first-letter和应用text-transform:capitalize; 
 因此,请尝试为此创build类,以便全局使用它,例如: .first-letter-uppercase并在CSS中添加如下所示的内容: 
 .first-letter-uppercase:first-letter { text-transform:capitalize; } 
另外的select是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' 
如果你想重复使用它,最好将它附加到JavaScript本地的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' 
 var str = "ruby java"; alert(str.charAt(0).toUpperCase() + str.substring(1)); 
 它会返回"Ruby java" 
http://jsfiddle.net/amitpandya/908c8e2v/
结果链接在jsfiddle
CoffeeScript的
 ucfirst = (str) -> str.charAt(0).toUpperCase() + str.slice(1) 
作为String原型的方法:
 String::capitalize = -> @charAt(0).toUpperCase() + @slice(1) 
One possible solution:
 function ConvertFirstCharacterToUpperCase(text) { return text.substr(0, 1).toUpperCase() + text.substr(1); } 
用这个:
  alert(ConvertFirstCharacterToUpperCase("this is string")); 
Here is working JS Fiddle