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
  • 7,345
  • 11
  • 42
  • 72
  • 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
  • 683,504
  • 96
  • 985
  • 979
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
  • 100,477
  • 16
  • 156
  • 200
2

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
  • 4,020
  • 4
  • 31
  • 45
1

Try,

function repeat(h, n) {
    var result = h;
    for (var i = 1; i < n; i++)
       result += h;
    return result;
}
chuckj
  • 27,773
  • 7
  • 53
  • 49