String.prototype.repeat()

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 2015 年 9 月以來,該特性已在各大瀏覽器中可用。

String 物件的 repeat() 方法建立一個新的字串,該字串包含指定數量的當前字串的副本,這些副本已連線在一起。

試一試

const mood = "Happy! ";

console.log(`I feel ${mood.repeat(3)}`);
// Expected output: "I feel Happy! Happy! Happy! "

語法

js
repeat(count)

引數

計數

一個介於 0Infinity 之間的整數,表示重複字串的次數。

返回值

一個包含指定數量的給定字串副本的新字串。

異常

RangeError

如果 count 為負數或 count 超過最大字串長度,則會丟擲錯誤。

示例

使用 repeat()

js
"abc".repeat(-1); // RangeError
"abc".repeat(0); // ''
"abc".repeat(1); // 'abc'
"abc".repeat(2); // 'abcabc'
"abc".repeat(3.5); // 'abcabcabc' (count will be converted to integer)
"abc".repeat(1 / 0); // RangeError

({ toString: () => "abc", repeat: String.prototype.repeat }).repeat(2);
// 'abcabc' (repeat() is a generic method)

規範

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

瀏覽器相容性

另見