Repeat the given string n times. Fastest implementation for repeating a string.
npx @tessl/cli install tessl/npm-repeat-string@1.6.0Repeat String is a high-performance string repetition utility that repeats a given string a specified number of times using an optimized algorithm. The library implements efficient caching and bit manipulation techniques to achieve superior performance compared to native JavaScript string repetition methods and other similar libraries.
npm install repeat-stringvar repeat = require('repeat-string');For ES modules (Node.js with CommonJS interop):
import repeat from 'repeat-string';Or with named import syntax:
import * as repeatString from 'repeat-string';
const repeat = repeatString.default;var repeat = require('repeat-string');
// Basic string repetition
repeat('A', 5);
//=> 'AAAAA'
// Repeat with spaces
repeat('abc ', 3);
//=> 'abc abc abc '
// Edge cases
repeat('x', 0); //=> ''
repeat('x', 1); //=> 'x'
repeat('x', 2); //=> 'xx'Repeat String uses an optimized bit manipulation algorithm with internal caching for maximum performance:
&, >>) for efficient string doublingRepeats a string n times with optimized performance using caching and bit manipulation.
/**
* Repeat the given string the specified number of times
* @param {string} str - The string to repeat
* @param {number|string} num - The number of times to repeat the string
* @returns {string} The repeated string
* @throws {TypeError} When str is not a string
*/
function repeat(str, num);Parameters:
str (string): The string to repeat. Must be a string value, throws TypeError otherwise.num (number|string): The number of times to repeat the string. Accepts both numbers and string representations of numbers. Values of 0, null, or undefined return empty string.Returns:
string: The input string repeated the specified number of times.Throws:
TypeError: When the first parameter is not a string. Error message: "expected a string"Usage Examples:
var repeat = require('repeat-string');
// Basic repetition
repeat('A', 5); //=> 'AAAAA'
repeat('hello', 3); //=> 'hellohellohello'
// String numbers work too
repeat('x', '10'); //=> 'xxxxxxxxxx'
// Edge cases
repeat('test', 0); //=> ''
repeat('test', 1); //=> 'test'
repeat('', 5); //=> ''
// Whitespace and special characters
repeat(' ', 5); //=> ' '
repeat('\\n', 3); //=> '\\n\\n\\n'
repeat('π', 3); //=> 'πππ'
// Error cases
repeat(123, 5); // Throws TypeError: expected a string
repeat(null, 5); // Throws TypeError: expected a stringThe library uses several optimization techniques:
This makes repeat-string significantly faster than native String.prototype.repeat() and other string repetition libraries, especially for repeated operations on the same string.