Create a string of variable length, filled with a repeated character

前端 未结 10 1094
刺人心
刺人心 2020-11-28 03:59

So, my question has been asked by someone else in it\'s Java form here: Java - Create a new String instance with specified length and filled with specific character. Best so

相关标签:
10条回答
  • 2020-11-28 04:37

    Based on answers from Hogan and Zero Trick Pony. I think this should be both fast and flexible enough to handle well most use cases:

    var hash = '####################################################################'
    
    function build_string(length) {  
        if (length == 0) {  
            return ''  
        } else if (hash.length <= length) {  
            return hash.substring(0, length)  
        } else {  
            var result = hash  
            const half_length = length / 2  
            while (result.length <= half_length) {  
                result += result  
            }  
            return result + result.substring(0, length - result.length)  
        }  
    }  
    
    0 讨论(0)
  • 2020-11-28 04:40

    ES2015 the easiest way is to do something like

    'X'.repeat(data.length)

    X being any string, data.length being the desired length.

    see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat

    0 讨论(0)
  • 2020-11-28 04:46

    I would create a constant string and then call substring on it.

    Something like

    var hashStore = '########################################';
    
    var Fiveup = hashStore.substring(0,5);
    
    var Tenup = hashStore.substring(0,10);
    

    A bit faster too.

    http://jsperf.com/const-vs-join

    0 讨论(0)
  • 2020-11-28 04:53

    Give this a try :P

    s = '#'.repeat(10)
    
    document.body.innerHTML = s

    0 讨论(0)
提交回复
热议问题