How to create a string with n characters? How to create a string with specific length? [duplicate]

This is a forward-looking answer, and won’t work in current implementations.

ECMAScript 6 is currently defining a String.prototype.repeat method. This will allow you to do:

var result = "x".repeat(65535);

Again, this is a future addition. Currently ECMAScript 6 (Harmony) is being drafted, and this could technically be removed, though it doesn’t seem likely.

Current draft:

15.5.4.21 String.prototype.repeat (count)

The following steps are taken:

  1. Let O be CheckObjectCoercible(this value).
  2. Let S be ToString(O).
  3. ReturnIfAbrupt(S).
  4. Let n be the result of calling ToInteger(count).
  5. ReturnIfAbrupt(n).
  6. If n < 0, then throw a RangeError exception.
  7. If n is +Infinity, then throw a RangeError exception.
  8. Let T be a String value that is made from n copies of S appended together. If n is 0, T is the empty String.
  9. Return T.

NOTE 1 This method creates a String consisting of the string elements of this object (converted to String) repeated
count time.

NOTE 2 The repeat function is intentionally generic; it does not require that its this value be a String object.Therefore, it can be transferred to other kinds of objects for use as a method.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)