1

Possible Duplicate:
Repeat String - Javascript

'h' x n;

Here n is a variable, and the generated string should be n times duplicate of h:

hh..h( n occurance of h in all)
Community
  • 1
  • 1
new_perl
  • 6,917
  • 10
  • 38
  • 69
  • 2
    Check out this answer: [Repeat String - Javascript][1] [1]: http://stackoverflow.com/questions/202605/repeat-string-javascript – Anas Karkoukli Sep 27 '11 at 03:33

4 Answers4

10

Here's a cute way to do it with no looping:

var n = 20;
var result = Array(n+1).join('h');

It creates an empty array of a certain length and then joins all the empty elements of the array putting your desired character between the empty elements - thus ending up with a string of all the same character n long.

You can see it work here: http://jsfiddle.net/jfriend00/PCweL/

jfriend00
  • 637,040
  • 88
  • 896
  • 906
3

If I understood your question following may be the solution.

var n = 10;
var retStr = "";
for(var i=0; i<n; ++i) {
retStr += "h";
}

return retStr;
Naved
  • 5,633
  • 4
  • 28
  • 46
2
String.prototype.repeat = function(n){
  var n = n || 0, s = '', i;
  for (i = 0; i < n; i++){
    s += this;
  }
  return s;
}

"h".repeat(5) // output: "hhhhh"

Something like that perhaps?

Brad Christie
  • 98,427
  • 16
  • 148
  • 198
1

Try,

function repeat(h, n) {
    var result = h;
    for (var i = 1; i < n; i++)
       result += h;
    return result;
}
chuckj
  • 25,575
  • 7
  • 51
  • 44