String.prototype.toString()

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

String 值的 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 物件包裝的字串。它的實現與 String.prototype.valueOf() 完全相同。

toString() 方法要求其 this 值是一個 String 原始值或包裝物件。對於其他 this 值,它會丟擲 TypeError,而不嘗試將其強制轉換為字串值。

由於 String 沒有 [Symbol.toPrimitive]() 方法,當 String 物件用於需要字串的上下文(例如在 模板字面量 中)時,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"

規範

規範
ECMAScript® 2026 語言規範
# sec-string.prototype.tostring

瀏覽器相容性

另見