JavaScriptのString
オブジェクトは、文字列を操作するための強力なオブジェクトです。文字列はJavaScriptにおいて非常に重要なデータ型であり、文字の並びを表します。String
オブジェクトは、プリミティブな文字列をラップするオブジェクトであり、文字列に対するさまざまな操作を行うメソッドを提供します。たとえば、文字列の検索、置換、文字列の結合、文字列の長さの取得などが可能です。JavaScriptでは、プリミティブ型の文字列でも自動的にString
オブジェクトに変換され、これらのメソッドを使用できます。
Stringオブジェクトのインスタンスメソッド
メソッド名 | 説明と注意点 |
---|---|
String.prototype.at(index) | 指定された位置の文字を返します。 注意点: 負のインデックスを指定して末尾から数えることができます。 |
String.prototype.charAt(index) | 指定された位置の文字を返します。 |
String.prototype.charCodeAt(index) | 指定された位置の文字のUTF-16コードを返します。 |
String.prototype.concat(...strings) | 指定された文字列を結合し、新しい文字列を返します。 |
String.prototype.endsWith(searchString, [length]) | 文字列が指定された文字列で終わるかを判定します。 |
String.prototype.includes(searchString, [position]) | 文字列が指定された部分文字列を含んでいるかどうかを判定します。 |
String.prototype.indexOf(searchString, [position]) | 指定された文字列の最初の出現箇所のインデックスを返します。 |
String.prototype.lastIndexOf(searchString, [position]) | 指定された文字列の最後の出現箇所のインデックスを返します。 |
String.prototype.localeCompare(compareString) | ロケールを考慮して2つの文字列を比較し、ソート順を示す数値を返します。 |
String.prototype.match(regexp) | 正規表現に一致する部分を検索し、結果を配列で返します。 |
String.prototype.matchAll(regexp) | 正規表現に一致するすべての結果を返します。 |
String.prototype.normalize([form]) | Unicode正規化形式で文字列を返します。 |
String.prototype.padEnd(targetLength, [padString]) | 文字列の末尾に指定された長さまで文字を埋めます。 |
String.prototype.padStart(targetLength, [padString]) | 文字列の先頭に指定された長さまで文字を埋めます。 |
String.prototype.repeat(count) | 指定された回数だけ文字列を繰り返して返します。 |
String.prototype.replace(searchValue, replaceValue) | 文字列内の一部を置換して新しい文字列を返します。 |
String.prototype.replaceAll(searchValue, replaceValue) | 文字列内のすべての一致部分を置換して新しい文字列を返します。 |
String.prototype.search(regexp) | 正規表現に一致する位置を検索します。 |
String.prototype.slice(beginIndex, [endIndex]) | 文字列の一部を抽出して新しい文字列を返します。 |
String.prototype.split([separator], [limit]) | 文字列を区切り文字で分割して配列を返します。 |
String.prototype.startsWith(searchString, [position]) | 文字列が指定された文字列で始まるかどうかを判定します。 |
String.prototype.substring(indexStart, [indexEnd]) | 指定された範囲の部分文字列を返します。 |
String.prototype.toLowerCase() | 文字列を小文字に変換します。 |
String.prototype.toUpperCase() | 文字列を大文字に変換します。 |
String.prototype.trim() | 文字列の先頭と末尾の空白を取り除きます。 |
String.prototype.trimEnd() | 文字列の末尾の空白を取り除きます。 |
String.prototype.trimStart() | 文字列の先頭の空白を取り除きます。 |
String.prototype.valueOf() | Stringオブジェクトのプリミティブな値を返します。 |
Stringオブジェクトの静的メソッド
メソッド名 | 説明と注意点 |
---|---|
String.fromCharCode(...codes) | 指定されたUTF-16コード単位に対応する文字列を返します。 |
String.fromCodePoint(...codePoints) | 指定されたコードポイントに対応する文字列を返します。 |
String.raw(template, ...substitutions) | テンプレートリテラルの「生」の文字列を返します。 |