w3resource

JavaScript: Create a new string of specified copies of a given string

JavaScript Basic: Exercise-57 with Solution

Write a JavaScript program to create one string of specified copies (positive numbers) of a given string.

Pictorial Presentation:

JavaScript: Create a new string of specified copies of a given string

Sample Solution:

JavaScript Code:

// Define a function named string_copies with parameters str (string) and n (number)
function string_copies(str, n) {
  // Check if n is less than 0
  if (n < 0)
    // Return false if n is negative
    return false;
  else
    // Use the repeat method to replicate the string 'n' times
    return str.repeat(n);
}

// Log the result of calling string_copies with the arguments "abc" and 5 to the console
console.log(string_copies("abc", 5));
// Log the result of calling string_copies with the arguments "abc" and 0 to the console
console.log(string_copies("abc", 0));
// Log the result of calling string_copies with the arguments "abc" and -2 to the console
console.log(string_copies("abc", -2)); 

Sample Output:

abcabcabcabcabc

false

Live Demo:

See the Pen JavaScript - create a new string of specified copies (positive number) of a given string. - basic-ex-57 by w3resource (@w3resource) on CodePen.


Flowchart:

Flowchart: JavaScript - Create a new string of specified copies of a given string

ES6 Version:

// Define a function named string_copies with parameters str and n
const string_copies = (str, n) => {
    // Check if n is less than 0, and return false if true
    if (n < 0) {
        return false;
    } else {
        // Use the repeat method to repeat the string n times
        return str.repeat(n);
    }
};

// Call the function with sample arguments and log the results to the console
console.log(string_copies("abc", 5));
console.log(string_copies("abc", 0));
console.log(string_copies("abc", -2));

Previous: JavaScript program to divide two positive numbers and return a string with properly formatted commas.
Next: JavaScript program to create a new string of 4 copies of the last 3 characters of a given original string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.