Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docs コミュニティーについてもっと知り、仲間になるにはこちらから。

String.prototype.toString()

BaselineWidely available

toString() メソッドは指定されたオブジェクトを表す文字列を返します。

試してみましょう

const stringObj = new String("foo");console.log(stringObj);// Expected output: String { "foo" }console.log(stringObj.toString());// Expected output: "foo"

構文

js
toString()

返値

呼び出したオブジェクトを表す文字列です。

詳細

そのString オブジェクトは、ObjecttoString メソッドを上書きします。つまり、Object.prototype.toString() を継承しません。String オブジェクトのtoString メソッドは、そのオブジェクトを表す文字列を返します(String.prototype.valueOf() と同等です)。

toString() メソッドはthis 値がString プリミティブまたはラッパーオブジェクトであることを要求します。他のthis の値に対しては、文字列値に変換しようとせずにTypeError を発生します。

String には[Symbol.toPrimitive]() メソッドがないため、JavaScript はtoString() メソッドを、文字列が求められるコンテキスト、例えばテンプレートリテラルString オブジェクトが使用されると、自動的に呼び出します。しかし、文字列プリミティブ値は文字列に変換するためにtoString() を呼び出しません。既に文字列なので、変換が実施されないからです。

js
String.prototype.toString = () => "Overridden";console.log(`${"foo"}`); // "foo"console.log(`${new String("foo")}`); // "Overridden"

toString() メソッドを使う

以下の例は、String オブジェクトを表す文字列の値を表示します。

js
const x = new String("Hello world");console.log(x.toString()); // "Hello world"

仕様書

Specification
ECMAScript® 2026 Language Specification
# sec-string.prototype.tostring

ブラウザーの互換性

関連情報

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp