所以,我的问题已经被其他人以Java形式在这里问了:Java -创建一个新的字符串实例,具有指定的长度和填充特定的字符。最好的解决方案?

……但我正在寻找它的JavaScript等效。

基本上,我想动态填充文本字段与“#”字符,基于每个字段的“maxlength”属性。因此,如果一个输入有maxlength="3",那么该字段将被"###"填充。

理想情况下,应该有类似Java StringUtils的东西。repeat("#", 10);,但是,到目前为止,我能想到的最好的选择是循环遍历和追加"#"字符,一次一个,直到达到最大长度。我总觉得还有比这更有效的方法。

什么好主意吗?

供您参考-我不能简单地在输入中设置默认值,因为“#”字符需要在焦点上清除,并且,如果用户没有输入值,将需要在模糊上“重新填充”。我所关心的是“补充”步骤


当前回答

一个很好的ES6选项是padStart一个空字符串。是这样的:

var str = ''.padStart(10, "#");

注意:这将不会在IE中工作(没有polyfill)。

其他回答

根据霍根和零戏法小马的回答。我认为这应该足够快速和灵活,以处理大多数用例:

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)  
    }  
}  

试一试:P

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

For Evergreen browsers, this will build a staircase based on an incoming character and the number of stairs to build.
function StairCase(character, input) {
    let i = 0;
    while (i < input) {
        const spaces = " ".repeat(input - (i+1));
        const hashes = character.repeat(i + 1);
        console.log(spaces + hashes);
        i++;
    }
}

//Implement
//Refresh the console
console.clear();
StairCase("#",6);   

您还可以为旧浏览器添加重复填充

    if (!String.prototype.repeat) {
      String.prototype.repeat = function(count) {
        'use strict';
        if (this == null) {
          throw new TypeError('can\'t convert ' + this + ' to object');
        }
        var str = '' + this;
        count = +count;
        if (count != count) {
          count = 0;
        }
        if (count < 0) {
          throw new RangeError('repeat count must be non-negative');
        }
        if (count == Infinity) {
          throw new RangeError('repeat count must be less than infinity');
        }
        count = Math.floor(count);
        if (str.length == 0 || count == 0) {
          return '';
        }
        // Ensuring count is a 31-bit integer allows us to heavily optimize the
        // main part. But anyway, most current (August 2014) browsers can't handle
        // strings 1 << 28 chars or longer, so:
        if (str.length * count >= 1 << 28) {
          throw new RangeError('repeat count must not overflow maximum string size');
        }
        var rpt = '';
        for (;;) {
          if ((count & 1) == 1) {
            rpt += str;
          }
          count >>>= 1;
          if (count == 0) {
            break;
          }
          str += str;
        }
        // Could we try:
        // return Array(count + 1).join(this);
        return rpt;
      }
    } 

我会这么做

Buffer.alloc(length, character).toString()

我会创建一个常量字符串,然后在它上面调用substring。

类似的

var hashStore = '########################################';

var Fiveup = hashStore.substring(0,5);

var Tenup = hashStore.substring(0,10);

也快了一点。

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