JavaScript: Repeat a string a specified times
JavaScript String: Exercise-21 with Solution
Repeat String Multiple Times
Write a JavaScript function to repeat a string for a specified time.
Test Data:
console.log(repeat_string('a', 4));
console.log(repeat_string('a'));
Output:
"aaaa"
"Error in string or count."
Visual Presentation:

Sample Solution:
JavaScript Code:
Output:
aaaa Error in string or count. Error in string or count. Error in string or count.
Explanation:
In the exercise above,
- The function "repeat_string(()" takes two parameters: 'string' (the string to repeat) and 'count' (the number of times to repeat the string).
- It checks for various conditions such as if the input string is null, if the count is negative, if the count is Infinity, or if the count is null. If any of these conditions are met, it returns an error message.
- It converts the count to an integer using a bitwise OR operation with 0 to ensure it's a non-negative integer (floor count).
- It then creates a new string by repeating the input string 'count' times using the "Array.join()" method.
- Finally, it tests the "repeat_string()" function with different arguments and logs the results to the console.
Flowchart:

Live Demo:
For more Practice: Solve these Related Problems:
- Write a JavaScript function that repeats a given string a specified number of times and returns the concatenated result.
- Write a JavaScript function that validates the repeat count and returns an error if it is not a positive integer.
- Write a JavaScript function that uses a loop to accumulate the repeated string without using built-in repeat().
- Write a JavaScript function that tests edge cases, such as repeating a string zero times, and returns an appropriate message.
Improve this sample solution and post your code through Disqus.
Previous: Write a JavaScript function that can pad (left, right) a string to get to a determined length.
Next: Write a JavaScript function to get a part of string after a specified character.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.