Repeat Character N Times

后端 未结 23 2529
栀梦
栀梦 2020-11-22 11:51

In Perl I can repeat a character multiple times using the syntax:

$a = \"a\" x 10; // results in \"aaaaaaaaaa\"

Is there a simple way to ac

相关标签:
23条回答
  • 2020-11-22 12:33

    In a new ES6 harmony, you will have native way for doing this with repeat. Also ES6 right now only experimental, this feature is already available in Edge, FF, Chrome and Safari

    "abc".repeat(3) // "abcabcabc"
    

    And surely if repeat function is not available you can use old-good Array(n + 1).join("abc")

    0 讨论(0)
  • 2020-11-22 12:33
    Array(10).fill('a').join('')
    

    Although the most voted answer is a bit more compact, with this approach you don't have to add an extra array item.

    0 讨论(0)
  • 2020-11-22 12:33

    Right pads with zeros with no arrays or loops. Just uses repeat() using ES6 2015, which has wide support now. Left pads if you switch the concatenation.

    function pad(text, maxLength){ 
      var res = text + "0".repeat(maxLength - text.length);
      return res;
    }
    
    console.log(pad('hello', 8)); //hello000
    
    0 讨论(0)
  • 2020-11-22 12:34

    An alternative is:

    for(var word = ''; word.length < 10; word += 'a'){}
    

    If you need to repeat multiple chars, multiply your conditional:

    for(var word = ''; word.length < 10 * 3; word += 'foo'){}
    

    NOTE: You do not have to overshoot by 1 as with word = Array(11).join('a')

    0 讨论(0)
  • 2020-11-22 12:37

    Can be used as a one-liner too:

    function repeat(str, len) {
        while (str.length < len) str += str.substr(0, len-str.length);
        return str;
    }
    
    0 讨论(0)
提交回复
热议问题