String.prototype.toString()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
toString()
メソッドは指定されたオブジェクトを表す文字列を返します。
試してみましょう
const stringObj = new String("foo");
console.log(stringObj);
// Expected output: String { "foo" }
console.log(stringObj.toString());
// Expected output: "foo"
構文
toString()
返値
呼び出したオブジェクトを表す文字列です。
詳細
その String
オブジェクトは、Object
の toString
メソッドを上書きします。つまり、Object.prototype.toString()
を継承しません。String
オブジェクトの toString
メソッドは、そのオブジェクトを表す文字列を返します(String.prototype.valueOf()
と同等です)。
toString()
メソッドは this
値が String
プリミティブまたはラッパーオブジェクトであることを要求します。他の this
の値に対しては、文字列値に変換しようとせずに TypeError
を発生します。
String
には [@@toPrimitive]()
メソッドがないため、JavaScript は toString()
メソッドを、文字列が求められるコンテキスト、例えばテンプレートリテラルで String
オブジェクトが使用されると、自動的に呼び出します。しかし、文字列プリミティブ値は文字列に変換するために toString()
を呼び出しません。既に文字列なので、変換が実施されないからです。
String.prototype.toString = () => "Overridden";
console.log(`${"foo"}`); // "foo"
console.log(`${new String("foo")}`); // "Overridden"
例
toString() メソッドを使う
以下の例は、String
オブジェクトを表す文字列の値を表示します。
const x = new String("Hello world");
console.log(x.toString()); // "Hello world"
仕様書
Specification |
---|
ECMAScript® 2025 Language Specification # sec-string.prototype.tostring |
ブラウザーの互換性
Report problems with this compatibility data on GitHubdesktop | mobile | server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
toString |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support