Uploaded on Oct 12, 2026
Learn how to generate a random string in JavaScript and Python. Get secure code for 32-character strings, random words, lorem text, plus FAQs.
generate-random-string-article
How to Generate a Random String: The
Complete Guide (JavaScript, Python and
Secure Methods)
Last updated: October 2026 | Reading time: 8 minutes
Quick answer: To generate a random string, pick a character set (letters, digits, symbols), choose a
length, and select characters from that set at random until you reach the length. In JavaScript, use
crypto.getRandomValues() for secure strings or Math.random() for non-sensitive ones. In Python, use the
secrets module for secure strings and random for everything else.
Key Takeaways
• A random string is a sequence of characters chosen unpredictably from a defined character set.
• Use a cryptographically secure source (crypto in JS, secrets in Python) for passwords, tokens,
API keys and session IDs.
• Math.random() and Python's random module are fast but predictable, so never use them for
security.
• A 32-character string drawn from 62 characters (a-z, A-Z, 0-9) has roughly 190 bits of entropy,
which is more than enough for most security needs.
• Random text such as words or lorem ipsum is generated differently from random strings and has
its own tools.
What Is a Random String?
A random string is a series of characters, such as aZ9xQ2mP, where each character is selected without a
predictable pattern. Developers use random strings for:
• Passwords and temporary passcodes
• API keys, access tokens and session IDs
• Unique file names and database identifiers
Scriptbaker | How to Generate a Random String Page 1
• Coupon and invite codes
• Test data and placeholder content
The quality of a random string depends on two things: the character set (the pool of allowed
characters) and the randomness source (how unpredictable the selection is).
What Is a Random Generator?
A random generator is a tool or algorithm that produces unpredictable values such as numbers,
characters, words or strings. There are two main types:
Type How it works Best for Secure?
Pseudo-random Uses a mathematical Games, simulations, test No
number generator formula and a starting data, shuffling
(PRNG) value called a seed
Cryptographically Uses operating-system Passwords, tokens, keys, Yes
secure PRNG (CSPRNG) entropy such as hardware encryption
events
A true random number generator (TRNG) uses physical phenomena such as atmospheric noise or
thermal noise. Most applications rely on a CSPRNG, which is secure enough for production use.
How to Generate Random in JS?
JavaScript offers two built-in ways to generate random values.
What Does Random random() Return?
Math.random() in JavaScript, and random.random() in Python, return a floating-point number from 0
(inclusive) up to, but not including, 1. For example: 0.7382915.
To get a random integer in a range, scale and round the result:
// Random integer between min and max (inclusive)
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randomInt(1, 100)); // e.g. 57
In Python:
import random
print(random.random()) # e.g. 0.6394267984578837
print(random.randint(1, 100)) # e.g. 57
Secure Random Values in JavaScript
For anything security-related, use the Web Crypto API:
const array = new Uint32Array(1);
crypto.getRandomValues(array);
console.log(array[0]); // secure random 32-bit integer
crypto.getRandomValues() works in modern browsers and in Node.js.
Scriptbaker | How to Generate a Random String Page 2
How to Create a Random String in JS?
Method 1: Quick and Simple (Not Secure)
function randomString(length) {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
for (let i = 0; i < length; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
return result;
}
console.log(randomString(10)); // e.g. "kT4mZp9QaX"
This is fine for demo data, UI keys and non-sensitive IDs.
Method 2: Cryptographically Secure (Recommended)
function secureRandomString(length) {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const values = new Uint32Array(length);
crypto.getRandomValues(values);
let result = '';
for (let i = 0; i < length; i++) {
result += chars[values[i] % chars.length];
}
return result;
}
console.log(secureRandomString(16));
The modulo operation introduces a very small bias when the character count doesn't divide evenly
into 2^32. For high-stakes use, apply rejection sampling or use a vetted library.
Method 3: One-Liners
// Short, non-secure
Math.random().toString(36).substring(2, 12);
// Secure unique identifier (UUID v4)
crypto.randomUUID();
crypto.randomUUID() returns a 36-character identifier like 3b241101-e2bb-4255-8caf-4136c566a962. It is
the easiest secure option when you need a unique ID rather than a custom-length string.
How to Generate a Random String in Python?
import secrets
import string
def secure_random_string(length):
alphabet = string.ascii_letters + string.digits
return ''.join(secrets.choice(alphabet) for _ in range(length))
print(secure_random_string(16))
For URL-safe tokens, Python also offers secrets.token_urlsafe(16) and secrets.token_hex(16).
How Can I Generate a Random 32-Character String?
A 32-character random string is a common length for API keys, tokens and salts. Here are the quickest
ways.
Scriptbaker | How to Generate a Random String Page 3
JavaScript (secure):
const random32 = secureRandomString(32);
Node.js (hex, 32 characters):
const { randomBytes } = require('crypto');
const token = randomBytes(16).toString('hex'); // 16 bytes = 32 hex characters
Python:
import secrets
token = secrets.token_hex(16) # 32 hex characters
Linux or macOS terminal:
openssl rand -hex 16
# or
tr -dc 'A-Za-z0-9'
words[Math.floor(Math.random() * words.length)]
).join(' ');
console.log(sentence);
Scriptbaker | How to Generate a Random String Page 4
How Can I Generate 20 Random Words?
Use a word list and pick 20 entries at random.
JavaScript with the random-words package:
import { generate } from 'random-words';
console.log(generate(20)); // array of 20 random words
Python using a word list file:
import random
with open('/usr/share/dict/words') as f:
words = f.read().splitlines()
print(random.sample(words, 20))
random.sample() guarantees no repeats, while random.choices() allows duplicates.
No-code option: Use an online random word generator, set the count to 20, and copy the output.
How to Generate Lorem Text in HTML?
HTML has no built-in lorem ipsum feature, but there are three easy ways to add placeholder text.
1. Emmet Shortcut (Fastest)
In VS Code, Sublime Text and most modern editors, type the following and press Tab:
p>lorem20
This expands to a paragraph with 20 words of lorem ipsum. Use lorem alone for the default 30 words,
or lorem100 for 100.
2. Lorem Ipsum Generator Websites
Sites such as lipsum.com let you choose paragraphs, words or bytes, then paste the result into your
HTML.
3. JavaScript
document.getElementById('placeholder').textContent =
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore.';
Remember to replace placeholder text with real content before launch, since search engines favor
useful, original copy.
Random String Best Practices
1. Match the tool to the risk. Use a CSPRNG for anything an attacker could benefit from guessing.
2. Never seed a secure generator manually. Let the operating system provide entropy.
3. Pick sufficient length. Aim for at least 128 bits of entropy for tokens and keys.
4. Choose the right character set. Use URL-safe characters (A-Z a-z 0-9 - _) for tokens placed in
links.
5. Avoid look-alike characters (0, O, l, 1) in codes users must type by hand.
Scriptbaker | How to Generate a Random String Page 5
6. Don't roll your own cryptography. Use trusted libraries such as nanoid, uuid or your language's
standard security module.
7. Store secrets safely. Hash passwords and keep API keys in environment variables, not in source
code.
Common Mistakes to Avoid
• Using Math.random() for passwords or tokens
• Generating strings that are too short (under 8 characters for passwords, under 16 for tokens)
• Reusing the same random string across users or sessions
• Logging secrets in plain text
• Assuming a random string is unique (collisions are possible, so check or use UUIDs where
uniqueness matters)
Frequently Asked Questions
How to generate a random string?
Define a character set, choose a length, and select characters from the set using a random source. In
JavaScript, loop with crypto.getRandomValues(). In Python, use secrets.choice() or
secrets.token_urlsafe(). For a quick result without coding, use an online random string generator.
How can I generate a random 32-character string?
Use crypto.randomBytes(16).toString('hex') in Node.js, secrets.token_hex(16) in Python, or openssl
rand -hex 16 in a terminal. Each produces 32 hexadecimal characters. For letters and digits, loop 32
times over a 62-character set using a secure random source.
What does random random() return?
random() returns a pseudo-random floating-point number greater than or equal to 0 and less than 1. In
JavaScript this is Math.random(), and in Python it is random.random(). Multiply and round the result to
get integers in any range you need.
How to generate random in JS?
Use Math.random() for general randomness, such as Math.floor(Math.random() * 10) for a number from
0 to 9. For secure randomness, use crypto.getRandomValues() or crypto.randomUUID().
How to create a random string in JS?
Create a character set string, loop for your desired length, and append one random character per
iteration. Use Math.random() for casual use or crypto.getRandomValues() for secure strings. A shortcut is
Math.random().toString(36).substring(2, 12).
How can I generate random text?
Use an online random text generator, a code snippet that picks words from an array, or a library such
as Faker or random-words. Choose lorem ipsum for layout placeholders and word-based generators for
realistic test data.
How can I generate 20 random words?
Use random-words in JavaScript with generate(20), or Python's random.sample(words, 20) with a word list.
Online word generators also let you set the exact count and copy the results instantly.
Scriptbaker | How to Generate a Random String Page 6
How to generate lorem text in HTML?
Type p>lorem20 in an Emmet-enabled editor and press Tab to expand 20 words of placeholder text.
Alternatively, copy text from a lorem ipsum website or insert it with JavaScript. HTML itself has no
native lorem generator.
What is a random generator?
A random generator is a tool or algorithm that produces unpredictable numbers, characters, words or
strings. Pseudo-random generators use formulas and seeds, while cryptographically secure
generators use system entropy to protect passwords, tokens and encryption keys.
Conclusion
Generating a random string is simple once you understand the two choices that matter: the
character set and the randomness source. Use Math.random() or Python's random module for casual
tasks, and switch to crypto or secrets whenever security is involved. Add the right length, URL-safe
characters and good storage habits, and your strings will be both unique and safe.
Need Help With Your Website or Digital Growth?
Whether you need secure, scalable development or content that ranks on Google and gets cited by AI
search tools, Scriptbaker can help. Our team delivers technical SEO, high-quality content and web
solutions built for visibility and results.
Contact Scriptbaker today for a free consultation and turn your website into a traffic-generating
asset.
Scriptbaker | How to Generate a Random String Page 7
Comments