JavaScript の repeat() で文字列を繰り返す方法と上限

JavaScript で同じ文字列をつなげるには text.repeat(count) を使います。'abc'.repeat(2) は 'abcabc' を返します。回数が 0 の場合は空文字列です。

文字列を繰り返す

元の値は変わりません。repeat() はコピーの間に区切り文字を入れません。間だけに区切りを入れるには、配列を作って Array(3).fill('ab').join('-') のように結合できます。

const text = 'abc';
console.log(text.repeat(0)); // ''
console.log(text.repeat(2)); // 'abcabc'
console.log(text); // 'abc'
console.log('-'.repeat(5)); // '-----'
console.log(Array(3).fill('ab').join('-')); // 'ab-ab-ab'

回数の変換と RangeError を理解する

メソッドは、最初に回数を整数または無限大に変換します。小数部分はゼロに近づく方向に切り捨てるため、2.9 は 2、-0.8 は 0 として扱われます。変換後の値が負または正の無限大なら RangeError になります。ECMAScript · String.prototype.repeat()

console.log('ab'.repeat(2.9));  // 'abab'
console.log('ab'.repeat(-0.8)); // ''
console.log('ab'.repeat());    // ''
console.log('ab'.repeat(NaN)); // ''

for (const count of [-1, Infinity]) {
  try {
    'ab'.repeat(count);
  } catch (error) {
    console.log(error.name); // 'RangeError'
  }
}

回数を省略した場合や NaN を渡した場合は空文字列になります。整数を入力する欄では、空欄かどうかと許可する範囲を明示的に確認します。正しい回数でも、結果が実行環境の対応する文字列長を超えると失敗することがあります。

サンプルで回数と結果の長さを制限する

コードを UTF-8 の string-repeat.html として保存し、ブラウザーで開きます。この例は空欄、小数、負数、21以上の回数を拒否します。繰り返す前に word.value.length * times が1,000以下であることも確認します。どちらもこのサンプルの上限です。

<!doctype html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>文字列を繰り返すサンプル</title>
</head>
<body>
<label for="word">繰り返す文字列</label>
<input id="word" value="abc">
<label for="count">繰り返し回数(0〜20)</label>
<input id="count" type="number" min="0" max="20" step="1" value="2">
<button id="run" type="button">繰り返す</button>
<pre id="result" aria-live="polite"></pre>
<script>
const word = document.querySelector('#word');
const count = document.querySelector('#count');
const result = document.querySelector('#result');

function update() {
  const times = Number(count.value);
  if (count.value.trim() === '' || !Number.isInteger(times) || times < 0 || times > 20) {
    result.textContent = "0〜20の整数を入力してください。";
    return;
  }
  if (word.value.length * times > 1000) {
    result.textContent = "結果はUTF-16コード単位で1,000以下にしてください。";
    return;
  }
  const repeated = word.value.repeat(times);
  result.textContent = `結果: ${JSON.stringify(repeated)}\n` +
    `文字列の長さ: ${repeated.length}`;
}

document.querySelector('#run').addEventListener('click', update);
update();
</script>
</body>
</html>

初期値の abc と 2 では abcabc と長さ6が表示されます。0を入力すると空文字列と長さ0になり、回数を空欄にすると案内が出ます。🙂 を2回繰り返すと絵文字は2個、長さは4です。length は UTF-16 コード単位 を数えるためです。

結果の長さには回数と別の上限があります。ASCIIの英字51個を20回繰り返すと1,020コード単位になるため、この例では文字列を作る前に案内を表示します。