Explain Codes LogoExplain Codes Logo

Repeat a string in JavaScript a number of times

javascript
prompt-engineering
performance
polyfills
Anton ShumikhinbyAnton Shumikhin·Nov 26, 2024
TLDR

To replicate a string in JavaScript, utilize the repeat() method:

console.log('abc'.repeat(3)); // prints 'abcabcabc'

The argument you pass to repeat() dictates the number of times the string is repeated.

Key considerations

Before deploying the repeat() method, make sure to check whether browser compatibility might be an issue. While most modern browsers are supportive, older versions might yield errors. To ensure your chosen browser is suitable, check out Can I use.

For older browsers, the Array join hack may be your best bet:

// 'cause an old dog can learn new tricks... or in this case, an old browser console.log(Array(4).join('abc')); // prints 'abcabcabc'

When dealing with larger strings or a high number of repetitions, performance matters. Different browsers may perform differently with each method. Always opt for some benchmarking to pinpoint the most performance-effective method for your use case.

In the unfortunate scenario where repeat() isn't available, try using a polyfill. This workaround provides the much-needed functionality:

if(!String.prototype.repeat) { // Not all heroes wear capes... some come in the form of fallback codes String.prototype.repeat = function(count) { return Array(count + 1).join(this); }; }

This polyfill extends legacy JavaScript environments and imbues them with the newer features.

Alternative approaches

Although repeat() is favorited by developers for its readability and conciseness, sometimes you may need to use an alternative approach.

For loop utilization

For those who need custom control over string repetition, assembling a for loop means you can build a string step-by step:

// 'cause sometimes we all need a "for" loop to lean on function repeatString(str, count) { let repeated = ''; for(let i = 0; i < count; i++) { repeated += str; } return repeated; } console.log(repeatString('abc', 3)); // prints 'abcabcabc'

The Array fill and join method

Combining Array.fill with the join() method offers another way to repeat strings:

// Array.fill meet join, join meet Array.fill... now make magic! console.log(Array(3).fill('abc').join('')); // prints 'abcabcabc'

Creating an array filled with the specific string and then joining these elements sans separators gets the tasks done.

Weigh the trade-offs

While choosing the best method for you, always keep a keen eye on the trade-offs between code conciseness and performance. High-stakes applications especially require you to determine which method is the most efficient.

Practical applications

Remember, every method has its place. In most web applications, repeat() method is the clear winner, but in a constrained resources environment a for loop or the polyfill could come in handy.

Generate precise formatting

When you're constructing strings that require precise formatting, the repeat() method becomes incredibly handy:

// Because a little bit of indentation never hurt anybody, did it? const indent = ' '.repeat(4); const indentedText = indent + "Indented line"; console.log(indentedText);

Create patterns

For creating visual patterns on a console log or web interface, the string repetition method is a no-brainer:

// Who needs a red carpet when you can roll out '#' console.log('#'.repeat(10)); // prints '##########'

Build polyfills for compatibility

When developing a library, consider making polyfills for the repeat() method to ensure compatibility with JavaScript environments that lack ES6 support.

Consider performance

In the world of large-scale text processing such as servers or games, always remember to benchmark and choose the method that best fits your constraints.