如何使字元串的第一個字母大寫,但不更改其他任何字母的大小寫?
例如:
-
->"this is a test"
"This is a test"
-
->"the Eiffel Tower"
"The Eiffel Tower"
-
->"/index.html"
"/index.html"
#1樓
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
其他一些答案修改了
String.prototype
(這個答案也曾經使用過),但是由于可維護性,我現在不建議這樣做(很難找出将函數添加到
prototype
,如果其他代碼使用相同的代碼,可能會導緻沖突。名稱/浏覽器會在将來添加具有相同名稱的本機功能)。
#2樓
這是一個稱為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()将大寫的首字母大寫 ,并将其與字元串的其餘部分(通過調用str.substr (1)找到)連接配接起來 。
您可能會認為這将導緻一個空字元串失敗,而實際上在像C這樣的語言中,您将不得不滿足這一要求。 但是,在JavaScript中,當您接受一個空字元串的子字元串時,您隻會得到一個空字元串。
#3樓
在CSS中:
p:first-letter {
text-transform:capitalize;
}
#4樓
yourString.replace(/^[a-z]/, function(m){ return m.toUpperCase() });
(如果您經常使用它,則可以将其封裝在一個函數中,甚至可以将其添加到String原型中。)
#5樓
我們可以使用我最喜歡的
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();
});
};
#6樓
var string = "hello world";
string = string.charAt(0).toUpperCase() + string.slice(1);
alert(string);
#7樓
在另一種情況下,我需要将其首字母大寫,将其餘字母小寫。 以下情況使我更改了此功能:
//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();
#8樓
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
#9樓
var str = "test string";
str = str.substring(0,1).toUpperCase() + str.substring(1);
#10樓
如果您使用underscore.js或Lo-Dash ,則underscore.string庫提供字元串擴充名,包括大寫:
_.capitalize(string)将字元串的首字母轉換為大寫。
例:
_.capitalize("foo bar") == "Foo bar"
#11樓
使用:
它将向控制台輸出
"Ruby java"
。
#12樓
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'
#13樓
簽出此解決方案:
var stringVal = 'master';
stringVal.replace(/^./, stringVal[0].toUpperCase()); // returns Master
#14樓
這是一種更加面向對象的方法:
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
您可以像下面這樣調用該函數:
"hello world".capitalize();
預期輸出為:
"Hello world"
#15樓
如果您對釋出的幾種不同方法的性能感興趣:
這是基于此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);
}
#16樓
如果您已經(或正在考慮)使用
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 js的第一個大寫字母:
function upperCaseFirst(str){
return str.charAt(0).toUpperCase() + str.substring(1);
}
#17樓
如果您這樣做,
ucfirst
函數将起作用。
function ucfirst(str) {
var firstLetter = str.slice(0,1);
return firstLetter.toUpperCase() + str.substring(1);
}
感謝JP的聲明。
#18樓
var capitalized = yourstring[0].toUpperCase() + yourstring.substr(1);
#19樓
僅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
- 我使用
名字capitalizeFirstChar
而不是capitalizeFirstChar
,因為OP并不要求使用代碼來大寫整個字元串中的第一個字母,而是大寫第一個字元(當然,如果是字母)。capitalizeFirstLetter
-
使我們能夠将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個操作/秒±1.2%。
- 使用JSBench.me在Google Chrome 57上建立。
#20樓
通常最好先使用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,如下所示:
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'
#21樓
String.prototype.capitalize = function(){
return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase();
} );
};
用法:
capitalizedString = someString.capitalize();
這是一個文本字元串=>這是一個文本字元串
#22樓
你可以像這樣一行
string[0].toUpperCase() + string.substring(1)
#23樓
這是2018 ECMAScript 6+解決方案 :
#24樓
yourString.replace(/\w/, c => c.toUpperCase())
我發現此箭頭功能最簡單。 Replace比對字元串的第一個字母字元(
\\w
),并将其轉換為大寫。 不需要任何愛好者。
#25樓
最短的 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
#26樓
有一個非常簡單的方法可以通過replace實作它。 對于ECMAScript 6:
'foo'.replace(/^./, str => str.toUpperCase())
結果:
'Foo'
#27樓
如果要重新格式化全部大寫的文本,則可能需要修改其他示例,例如:
function capitalize (text) {
return text.charAt(0).toUpperCase() + text.slice(1).toLowerCase();
}
這将確定更改以下文本:
TEST => Test
This Is A TeST => This is a test
#28樓
這是流行答案的簡化版本,它通過将字元串視為數組來獲得第一個字母:
function capitalize(s)
{
return s[0].toUpperCase() + s.slice(1);
}
更新:
根據下面的評論,這在IE 7或更低版本中不起作用。
更新2:
為了避免
undefined
空字元串(請參見下面的@ njzk2的注釋 ),您可以檢查一個空字元串:
function capitalize(s)
{
return s && s[0].toUpperCase() + s.slice(1);
}
#29樓
将字元串中所有單詞的首字母大寫:
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(" ");
}
#30樓
在CSS中似乎更容易:
<style type="text/css">
p.capitalize {text-transform:capitalize;}
</style>
<p class="capitalize">This is some text.</p>
這來自CSS文本轉換屬性 (位于W3Schools )。