JavaScript 首字母轉大寫的三種作法

Kunyu
Jun 12, 2021

--

Photo by Daria Nepriakhina on Unsplash

使用toUpperCase可以將字串轉成大寫,但若是想要只把首字母轉成大寫呢?就需要一點小技巧啦~

#1 運用charAt指定首字母並轉大寫,原本的字串則是切掉首字母,再把兩項接起來。

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

#2 運用ES5字串看成陣列的特性,直接存取索引值0將首字母轉大寫,後續與前項相同。

string[0].toUpperCase() + input.id.slice(1);

#3 使用replace取代選取內容,正規表達式當中/^./代表字串的第一個字母,取代成大寫。

string.replace(/^./, string[0].toUpperCase()); 

如何選擇?

我會使用我認為最簡單的#2方法,#3的正規表達式算是殺雞用牛刀了,#1則在我腦袋裡的連結沒有#2直覺,當然這會因人而異,也很歡迎大家分享選擇的理由。

來個範例

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Kunyu
Kunyu

Written by Kunyu

軟體工程師,Web系統開發為主。

No responses yet

Write a response