2

I'd like to insert a letter equal to the number returned by a calculation within my code :

var howmanytimes = 500 / 100;
$('#mytextmultiplied').text(howmanytimes*'whatiwanttowrite');

The last part is obviously wrong. Is looping the only option here?

Phil Ross
  • 25,590
  • 9
  • 67
  • 77
dyb
  • 59
  • 8

2 Answers2

3

Here's a technique:

var howmanytimes = 500 / 100;
var repeatedText = (howmanytimes < 1) ? '' : new Array(howmanytimes + 1).join(whatiwanttowrite);
$('#mytextmultiplied').text(repeatedText);

The above technique is not the fastest. For more efficient (but longer code-wise) techniques, see the answers in these similar questions:

Someday you will be able to use String.prototype.repeat

Community
  • 1
  • 1
John S
  • 21,212
  • 8
  • 46
  • 56
0

You need a for loop like this: fiddle

var howmanytimes = 500 / 100; 
 //create a loop - i variable increments on each loop until it reaches 'howmanytimes'
for(var i = 0; i <= howmanytimes ; i++) {
 //here is your code to run on each loop -  
    $('#mytextmultiplied').append('whatiwanttowrite' + "<br />");
}
Cory
  • 1,263
  • 16
  • 31