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

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

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

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

什么好主意吗?

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


当前回答

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

其他回答

试一试:P

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

(我所见过的)最好的方法是

var str = new Array(len + 1).join( character );

这将创建一个具有给定长度的数组,然后将其与给定的字符串连接以重复操作。.join()函数的作用是,不管元素是否赋值,数组的长度都是不变的,未定义的值会呈现为空字符串。

您必须在所需的长度上加上1,因为分隔符字符串位于数组元素之间。

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

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

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

如果你喜欢,你可以使用函数的第一行作为一行:

function repeat(str, len) {
    while (str.length < len) str += str.substr(0, len-str.length);
    return str;
}