Generates a random string with the specified length.
Array.from()
to create a new array with the specified length
.Math.random()
generate a random floating-point number.Number.prototype.toString()
with a radix
value of 36
to convert it to an alphanumeric string.String.prototype.slice()
to remove the integral part and decimal point from each generated number.Array.prototype.some()
to repeat this process as many times as required, up to length
, as it produces a variable-length string each time.String.prototype.slice()
to trim down the generated string if it's longer than the given length
.const randomAlphaNumeric = length => {
let s = '';
Array.from({ length }).some(() => {
s += Math.random().toString(36).slice(2);
return s.length >= length;
});
return s.slice(0, length);
};
randomAlphaNumeric(5); // '0afad'
JavaScript, String
Pads a string on both sides with the specified character, if it's shorter than the specified length
.
JavaScript, String
Truncates a string up to specified length, respecting whitespace when possible.
JavaScript, String
Truncates a string up to a specified length.