JavaScript/string
JavaScriptにおけるstringプリミティブは、文字列を表現するための基本的なデータ型です。プリミティブ型は、JavaScriptにおいて最も単純な値の型であり、オブジェクトではないため、プロパティやメソッドを持たないように思えますが、JavaScriptではstringプリミティブに対してメソッドを呼び出すことが可能です。これは、JavaScriptが内部的にプリミティブ値を対応するオブジェクトに自動的に変換するためです。
stringプリミティブの特徴
編集- 不変性(Immutable)
- stringプリミティブは不変(immutable)です。つまり、一度作成された文字列は変更できません。文字列を変更する操作(例: 連結、置換)を行うと、新しい文字列が生成されます。
- リテラル表現
- stringプリミティブは、シングルクォーテーション
'、ダブルクォーテーション"、またはバッククォート`(テンプレートリテラル)で囲まれた文字列として表現されます。
- 例:
const str1 = 'Hello'; const str2 = "World"; const str3 = <code>Hello, ${str2}!</code>; // テンプレートリテラル
- stringプリミティブは、シングルクォーテーション
- メソッドの利用
- stringプリミティブは、
Stringオブジェクトのメソッドを利用できます。JavaScriptは、プリミティブ値に対してメソッドを呼び出すと、一時的にStringオブジェクトに変換します。
- 例:
const str = "hello"; console.log(str.toUpperCase()); // "HELLO"
- stringプリミティブは、
- インデックスアクセス
- stringプリミティブは、文字のシーケンスとして扱われ、インデックスを使用して個々の文字にアクセスできます。
- 例:
const str = "hello"; console.log(str[0]); // "h"
- 長さの取得
lengthプロパティを使用して、文字列の長さを取得できます。
- 例:
const str = "hello"; console.log(str.length); // 5
stringプリミティブとStringオブジェクトの違い
編集JavaScriptには、stringプリミティブとStringオブジェクトの2つの文字列表現がありますが、通常はstringプリミティブを使用します。
- stringプリミティブ:
- 基本的なデータ型であり、リテラルで表現されます。メモリ効率が良く、不変です。
const strPrimitive = "hello"; console.log(typeof strPrimitive); // "string"
- Stringオブジェクト:
newキーワードを使用して明示的に作成されるオブジェクトです。プリミティブとは異なり、オブジェクト型です。const strObject = new String("hello"); console.log(typeof strObject); // "object"
- 注意点
Stringオブジェクトは、プリミティブとは異なる振る舞いをすることがあります。例えば、比較演算子を使用する場合、プリミティブは値で比較されますが、オブジェクトは参照で比較されます。
const str1 = "hello"; const str2 = new String("hello"); const str3 = new String("hello"); console.log(str1 === "hello"); // true console.log(str2 === "hello"); // false(オブジェクトとプリミティブの比較) console.log(str2 === str3); // false(オブジェクトとオブジェクトの比較)
stringプリミティブのメソッド例
編集stringプリミティブは、Stringオブジェクトのメソッドを利用できます。以下はその例です。
toUpperCase()/toLowerCase():- 文字列を大文字または小文字に変換します。
#: const str = "Hello"; #: console.log(str.toUpperCase()); // "HELLO" #: console.log(str.toLowerCase()); // "hello"
charAt(index):- 指定されたインデックスの文字を返します。
#: const str = "Hello"; #: console.log(str.charAt(1)); // "e"
substring(start, end):- 指定された範囲の部分文字列を返します。
#: const str = "Hello, World!"; #: console.log(str.substring(0, 5)); // "Hello"
indexOf(searchValue):- 指定された値が最初に現れるインデックスを返します。見つからない場合は
-1を返します。 #: const str = "Hello, World!"; #: console.log(str.indexOf("World")); // 7
- 指定された値が最初に現れるインデックスを返します。見つからない場合は
includes(searchValue):- 指定された値が含まれているかどうかを真偽値で返します。
#: const str = "Hello, World!"; #: console.log(str.includes("World")); // true
replace(searchValue, replaceValue):- 指定された値を別の値に置換します。
#: const str = "Hello, World!"; #: console.log(str.replace("World", "JavaScript")); // "Hello, JavaScript!"
まとめ
編集JavaScriptにおけるstringプリミティブは、文字列を表現するための基本的なデータ型であり、不変性、リテラル表現、メソッドの利用、インデックスアクセスなどの特徴を持ちます。通常はstringプリミティブを使用し、Stringオブジェクトは特別な場合を除いて使用しません。stringプリミティブは、文字列操作の基盤としてJavaScriptプログラミングにおいて重要な役割を果たします。