创建一个可变长度的字符串,填充重复的字符 [英] Create a string of variable length, filled with a repeated character

查看:149
本文介绍了创建一个可变长度的字符串,填充重复的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



。 。 。但我正在寻找它的JavaScript等价物。基本上,我想要根据maxlength属性动态地填充带#字符的文本字段每个领域。所以,如果一个输入有 maxlength =3,那么这个字段会被填充###。


$ b $理想情况下,会有类似Java StringUtils.repeat(#,10); 的东西,但到目前为止,我可以想到的最佳选择是循环并追加#字符,一次一个,直到达到最大长度。

有什么想法?



我不能动摇这种感觉,认为有更有效的方法可以做到这一点。仅供参考 - 我不能简单地在输入中设置默认值,因为#字符需要在焦点上清除,并且如果用户没有输入值,则需要重新填充模糊。这是我关心的重新填充步骤 解决方案

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

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

创建一个给定长度的数组,然后将其与给定的字符串连接以重复。 .join()函数不考虑元素是否赋值,未定义值是否为空字符串。



您必须将1添加到所需的长度,因为分隔符字符串在数组元素之间


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 solution?

. . . but I'm looking for its JavaScript equivalent.

Basically, I'm wanting to dynamically fill text fields with "#" characters, based on the "maxlength" attribute of each field. So, if an input has has maxlength="3", then the field would be filled with "###".

Ideally there would be something like the Java StringUtils.repeat("#", 10);, but, so far, the best option that I can think of is to loop through and append the "#" characters, one at a time, until the max length is reached. I can't shake the feeling that there is a more efficient way to do it than that.

Any ideas?

FYI - I can't simply set a default value in the input, because the "#" characters need to clear on focus, and, if the user didn't enter a value, will need to be "refilled" on blur. It's the "refill" step that I'm concerned with

解决方案

The best way to do this (that I've seen) is

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

That creates an array with the given length, and then joins it with the given string to repeat. The .join() function honors the array length regardless of whether the elements have values assigned, and undefined values are rendered as empty strings.

You have to add 1 to the desired length because the separator string goes between the array elements.

这篇关于创建一个可变长度的字符串,填充重复的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆