50
46

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScript で文字列の最初の文字を大文字にするための3つの方法

Last updated at Posted at 2012-12-26

JavaScript には文字列の最初の文字を大文字にする関数はありません。
PHPでいうと ucfirst 関数と同じことができる3つの方法を書いた。

var text = 'hello.';

var text2 = text.charAt(0).toUpperCase() + text.slice(1);

var text2 = text.substring(0, 1).toUpperCase() + text.substring(1);

var text2 = text.replace(/^[a-z]/g, function (val) {
    return val.toUpperCase();
});

// Output: Hello.

文字列の置き換え(replace)が遅いという先入観があって、1つ目の方法の charAt と slice を使うようにしてる。

ちなみに頭文字以外を小文字にしたい場合はこんな感じになる

var text = 'hEllo All.';

var text2 = text.charAt(0).toUpperCase() + text.slice(1).toLowerCase();

var text2 = text.substring(0, 1).toUpperCase() + text.substring(1).toLowerCase();

var text2 = text.toLowerCase().replace(/^[a-z]/g, function (val) {
    return val.toUpperCase();
});

var text2 = text.replace(/(^[a-z])(.*)/g, function (text, val1, val2) {
    return val1.toUpperCase() + val2.toLowerCase();
});

// Output: Hello all.
50
46
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
50
46

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?