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.

Phương thức repeat() của các giá trị String tạo và trả về một chuỗi mới chứa số lượng bản sao được chỉ định của chuỗi này, được nối lại với nhau.

Try it

const mood = "Happy! ";

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

Cú pháp

js
repeat(count)

Tham số

count

Một số nguyên trong khoảng từ 0 đến Infinity, cho biết số lần lặp lại chuỗi.

Giá trị trả về

Một chuỗi mới chứa số lượng bản sao được chỉ định của chuỗi đã cho.

Ngoại lệ

RangeError

Ném ra nếu count là số âm hoặc nếu count vượt quá độ dài chuỗi tối đa.

Ví dụ

Sử dụng 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)

Đặc tả

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

Tương thích trình duyệt

Xem thêm