Javascript String repeat(times)

Introduction

Javascript String repeat(times)

String.prototype.repeat = function(times) {
  return new Array(times+1).join(this);
};

console.log( "yes".repeat(3) ); // repeat three times

Javascript String repeat(times)

// i know that this hasn't been taught in the book, but
// it felt like the right way to do it.

String.prototype.repeat = function(times) {
   return (new Array(times + 1)).join(this);
};

for (i = 1; i <= 7; i++) {
  console.log('#'.repeat(i));
}

Javascript String repeat(times)

var str = 'hello';

console.log(typeOf(str.repeat)); // 'null'

String.prototype.repeat = function(times){
        var arr = [];
        while (times--) arr.push(this);
        return arr.join('');
};

console.log(typeOf(str.repeat)); // 'function'
console.log(str.repeat(3)); // 'hellohellohello'

Javascript String repeat(times)

// http://www.codewars.com/kata/put-a-letter-in-a-column

const buildRowText = (index, character) => {  
  return "| ".repeat(index + 1) + character + "| ".repeat(9 - index);
}

String.prototype.repeat = function(times){
    return new Array(times + 1).join(this).trim();
}



PreviousNext

Related