Prototype .repeat gives me error of invalid string length

Hello all,

I am facing a javascript coding challenge, which requires me to find all occurences of letter ‘a’ in a repeated string.
So, the given string needs to be repeated a respective number of times in order to be found the occurences of letter ‘a’ inside it and need to look at the ‘n’ number of letters from the string.

function repeatedString(s, n) {
    let count = 0;
    let repeated = "";
    s.length <= n ? repeated = s.repeat(Math.ceil(n/(s.length))) : repeated = s.repeat(Math.floor(n/(s.length)));
    //console.log(repeated, repeated.length);
    for (let i = 0; i <= n; i++) {
        if (repeated.split('')[i] == 'a') {
    return count;

console.log(repeatedString('abcac',10)); //abcacabcac
console.log(repeatedString('aba',10)); //abaabaabaa

Now, at the last console.log() test of ‘1000000000000’, i get the error of invalid string length.
I have checked MDN documentation for the repeat function, but I could find or understand why this high number isn’t a valid one for repetition.

How could I solve this problem? Is it a BigInt?

Appreciate every response in advance.

Running this code, there does seem to me a max:

const max = 1000000000000

for (let i = 1; i < max; i *= 2) {
  console.log(Math.log10(i), i)
  let s = 'a'.repeat(i)


This error depends on the implementation of the JS engine, which differs between browsers and nodejs. There is a max string length which is affected by the memory available too, so, if the length is big enough the engine may be running out of memory.

To fix it, you could use only mathematics to find the count. If s.length is 1 and s == ‘a’, then how many 'a’s would be if n = 2340000?

1 Like

A little deeper investigation shows that 536870889 seems to be the largest it can handle, at least in codepen.

1 Like

Yeah, I’m with skaparate.

It’s like someone says, “OK, there are 6 widgets in a box and 10,000 boxes. How many widgets are there?” And you are saying, “OK, the only way to figure it out is spread out 10,000 boxes and count the widgets.”. We think there is an easier way. That is unless I’ve horribly misunderstood something.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.