Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

Repeat a String Repeat a String

// Repeat a String Repeat a String

// Repeat a given string str (first argument) for num times (second argument).
// Return an empty string if num is not a positive number. For the purpose of this challenge, do not use the built-in .repeat() method.

function repeatStringNumTimes(str, num) {
	if (num < 0) return '';
	let result = '';
	for (let i = 0; i <= num - 1; i++) {
		result += str;
	}
	return result;
}

repeatStringNumTimes('abc', 3);

// OR

function repeatStringNumTimes(str, num) {
	var accumulatedStr = '';

	while (num > 0) {
		accumulatedStr += str;
		num--;
	}

	return accumulatedStr;
}

// OR

function repeatStringNumTimes(str, num) {
	if (num < 1) {
		return '';
	} else {
		return str + repeatStringNumTimes(str, num - 1);
	}
}

// OR

// my favourite
function repeatStringNumTimes(str, num) {
	return num > 0 ? str + repeatStringNumTimes(str, num - 1) : '';
}
Comment

String.repeat()

function doubleString(string) {
  return string.repeat(2);
}

// Should return 'echoecho'
console.log("doubleString('echo') returns: " + doubleString("echo"));
Comment

PREVIOUS NEXT
Code Example
Javascript :: export all functions from js file 
Javascript :: express get remote ip 
Javascript :: how to replace strings with react components 
Javascript :: check if value is boolean 
Javascript :: vue cors 
Javascript :: chart js change axis label 
Javascript :: ruby hash to json 
Javascript :: Javascript Get day number in year from date 
Javascript :: data-id html javascript 
Javascript :: ajax file form 
Javascript :: fonction fleche javascript 
Javascript :: js add key to object 
Javascript :: how to capitalize first letter in javascript 
Javascript :: React count up on scroll 
Javascript :: linear gradient react js 
Javascript :: js localstorage add text 
Javascript :: resize windows 
Javascript :: upload files to api using axios 
Javascript :: how to search for a voice channel within a guild using discord.js 
Javascript :: node require module 
Javascript :: what is startof() in moment 
Javascript :: javascript anagram 
Javascript :: react native share image 
Javascript :: discord js bot embed user profile picture 
Javascript :: downgrade nodejs with nvm 
Javascript :: vue js default props 
Javascript :: password confirmation using Joi 
Javascript :: javascript pseudo random 
Javascript :: iife javascript 
Javascript :: $q.platform.is.mobile 
ADD CONTENT
Topic
Content
Source link
Name
1+4 =