String.prototype.repeat()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2015.

repeat() 方法构造并返回一个新字符串,其中包含指定数量的所调用的字符串副本,这些副本连接在一起。

尝试一下

const mood = "Happy! ";

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

语法

js
repeat(count)

参数

count

介于 0+Infinity 之间的整数。表示在新构造的字符串中重复了多少遍原字符串。

返回值

包含指定字符串的指定数量副本的新字符串。

异常

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 将被转换为整数)
"abc".repeat(1 / 0); // RangeError

({ toString: () => "abc", repeat: String.prototype.repeat }).repeat(2);
// 'abcabc'(repeat() 是一个通用方法)

规范

Specification
ECMAScript® 2025 Language Specification
# sec-string.prototype.repeat

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
repeat

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

参见