How to create a specific number of copies of a string in JavaScript

3 Answers

0 votes
function createCopies(str, num) {
	let newStr = "";
	
	for (let i = 0; i < num; i++) {
		newStr += str;
	}

	return newStr;
}

let s = "abc";

s = createCopies(s, 3);
  
console.log(s);
  
  
  
/*
run:
  
abcabcabc
  
*/

 



answered Dec 23, 2024 by avibootz
0 votes
function createCopies(str, num) {
	return str.repeat(num);
}

let s = "abc";

s = createCopies(s, 3);
  
console.log(s);
  
  
  
/*
run:
  
abcabcabc
  
*/

 



answered Dec 23, 2024 by avibootz
0 votes
function createCopies(str, num) {
	return Array(num + 1).join(str) 
}

let s = "abc";

s = createCopies(s, 3);
  
console.log(s);
  
  
  
/*
run:
  
abcabcabc
  
*/

 



answered Dec 23, 2024 by avibootz
...