Hướng dẫn random string javascript

There is no best way to do this. You can do it any way you prefer, as long as the result suits your requirements. To illustrate, I've created many different examples, all which should provide the same end-result

Most other answers on this page ignore the upper-case character requirement.

Here is my fastest solution and most readable. It basically does the same as the accepted solution, except it is a bit faster.

function readableRandomStringMaker(length) {
  for (var s=''; s.length < length; s += 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'.charAt(Math.random()*62|0));
  return s;
}
console.log(readableRandomStringMaker(length));
// e3cbN

Here is a compact, recursive version which is much less readable:

const compactRandomStringMaker = (length) => length-- && "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".charAt(Math.random()*62|0) + (compactRandomStringMaker(length)||"");
console.log(compactRandomStringMaker(5));
// DVudj

A more compact one-liner:

Array(5).fill().map(()=>"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".charAt(Math.random()*62)).join("")
// 12oEZ

A variation of the above:

"     ".replaceAll(" ",()=>"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".charAt(Math.random()*62))

The most compact one-liner, but inefficient and unreadable - it adds random characters and removes illegal characters until length is l:

((l,f=(p='')=>p.lengthf())(5)

A cryptographically secure version, which is wasting entropy for compactness, and is a waste regardless because the generated string is so short:

[...crypto.getRandomValues(new Uint8Array(999))].map((c)=>String.fromCharCode(c).replace(/[^a-z0-9]/i,'')).join("").substr(0,5)
// 8fzPq

Or, without the length-argument it is even shorter:

((f=(p='')=>p.length<5?f(p+String.fromCharCode(Math.random()*123).replace(/[^a-z0-9]/i,'')):p)=>f())()
// EV6c9

Then a bit more challenging - using a nameless recursive arrow function:

((l,s=((l)=>l--&&"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".charAt(Math.random()*62|0)+(s(l)||""))) => s(l))(5);
// qzal4

This is a "magic" variable which provides a random character every time you access it:

const c = new class { [Symbol.toPrimitive]() { return "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".charAt(Math.random()*62|0) } };
console.log(c+c+c+c+c);
// AgMnz

A simpler variant of the above:

const c=()=>"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".charAt(Math.random()*62|0);
c()+c()+c()+c()+c();
// 6Qadw

Example 1: Generate Random Strings

// program to generate random strings

// declare all characters
const characters ='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

function generateString(length) {
    let result = ' ';
    const charactersLength = characters.length;
    for ( let i = 0; i < length; i++ ) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }

    return result;
}

console.log(generateString(5));

Output

B5cgH

In the above example, the Math.random() method is used to generate random characters from the specified characters (A-Z, a-z, 0-9).

The for loop is used to loop through the number passed into the generateString() function. During each iteration, a random character is generated.


Example 2: Generate Random Strings Using Built-in Methods

// program to generate random strings

const result = Math.random().toString(36).substring(2,7);
console.log(result);

Output

gyjvo

In the above example, built-in methods are used to generate random characters.

The Math.random() method generates the random number between 0 and 1.

In toString(36) method, 36 represents base 36. The toString(36) represents digits beyond 9 by letters.

The substring(2, 7) method returns five characters.

Note: In the above examples, the output varies each time because random characters are generated at every execution.

Hướng dẫn random string javascript

How to Generate a RANDOM STRING in JavaScript and HTML. Hey guys and gurls. Today I’ll be showing you how to generate and use a random string in JavaScript. Random strings are very useful in programming. They can be used when creating IDs. They can also be used to create random passwords. Here’s an example of a project I created using this code.

Ongoing, this has many applications and will definitely come in handy. Say no more. Because this is how to generate a random string in JavaScript and HTML.

Patreon –

Until next time
RhymBil Out

Tag: javascript random string, Rhymbil, rhymbil out, How to Generate a RANDOM STRING in JavaScript and HTML, generate random string, javascript, random, js, random string in javascript, javascript string tutorial, random password generator javascript, random password generator, random id generator, javascript id gen, generate random words javascript, generate random password, generate random iid javascript, generate random string javascript, html random string generator

Xem Thêm Bài Viết PC Khác: http://ứngdụng.vn/pc

Nguồn: http://ứngdụng.vn

Random Posts

Hướng dẫn random string javascript

Rate this post PDF Catalog for WooCommerce front end on Internet Explorer 9 and Firefox 30 under Windows 7 Tag:…

Hướng dẫn random string javascript

Rate this post Gracias por ver el video no te olvides suscribirte para mas contenido comparte y dale me gusta…

Hướng dẫn random string javascript

Rate this post Video HD 1 phút xóa Virus tự động mở các trình duyệt website không mong muốn trên…

Hướng dẫn random string javascript

Rate this post Setting up Dahua SmartPSS v2.02 Tag: idmss for pc, Smart PSS, dahua Xem Thêm Bài Viết Mobile…

Hướng dẫn random string javascript

Rate this post This playlist has been updated! Please check: what is instanceof … Tag: javascript instanceof, [vid_tags] Xem Thêm…

Hướng dẫn random string javascript

Rate this post Windows 10 đã và đang được rất nhiều người sử dụng. Nhưng hầu hết chúng ta đều…