使用 JavaScript 对字符串填充大小写随机字母
我们需要编写一个函数,它接收两个参数,第一个是字符串,第二个是数字。字符串的长度始终小于或等于该数字。我们必须在字符串末尾插入一些随机小写字母,以便它的长度恰好等于该数字,并且我们必须返回新字符串。
示例
让我们为这个函数编写代码 −
const padString = (str, len) => {
if(str.length < len){
const random = Math.floor(Math.random() * 26);
const randomAlpha = String.fromCharCode(97 + random);
return padString(str + randomAlpha, len);
};
return str;
};
console.log(padString('abc', 10));
console.log(padString('QWERTY', 10));
console.log(padString('HELLO', 30));
console.log(padString('foo', 10));输出
控制台中的输出 −
abckoniucl QWERTYcwaf HELLOdnulywbogqhypgmylqlvmckhg Foofhfnhon
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP