There are so many ways to generate random strings in JavaScript and it doesn”t really matter which method is faster.

The method I like using most is Math.random()

I made a video on it:

Basically the idea is to use Math.random(), then you can convert it to string and do some simple string manipulation on it.

To get random numbers, I would use something like below:

Đang xem: How to create random numbers & characters with javascript

Fortunate .toString() has a param called radix that you can pass in numbers between 2 – 36 which will cast the generated numbers to the radix characters that fall between the given number. The radix is also known as base and its for representing numeric values

To get a random number between 0-1:

const generateRandomString = function(length=6){return Math.random().toString(20).substr(2, length)}
That”s all.

If you know of any other faster ways, please I would love to see it in the comment section.

Thanks

*

Personal Moderator

*

Xem thêm: Công Thức Làm Rượu Nho Ủ Không Đường Đơn Giản, Để Được Lâu Tại Nhà

*

Nice function! But one thing I noticed is that this will only work for random alpha-numeric strings up to a certain length. If you want to have something longer, you should call the method recursively. Something like:

const generateRandomString = function (length, randomString=””) { randomString += Math.random().toString(20).substr(2, length); if (randomString.length > length) return randomString.slice(0, length); return generateRandomString(length, randomString);};

*

Xem thêm:

*

Hi, thanks for the simple, straight-forward article! I just wanted to point out a small error in your one-liner. You define the length variable, but you still used a hard-coded “6” instead of it in the expression.

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *