ภาพรวม
บทความนี้สาธิตวิธีสร้าง Random String ความยาว n ประกอบด้วยตัวอักษร a-z เท่านั้น
การนำไปใช้
const randomNameGenerator = (num) => {
let res = '';
for (let i = 0; i < num; i++) {
const random = Math.floor(Math.random() * 27); // Bug: 0-26 แต่ a-z มี 26 ตัว
res += String.fromCharCode(97 + random);
}
return res;
};
console.log(randomNameGenerator(8)); // kdcwping (ตัวอย่าง)
ผลลัพธ์
kdcwping
Bug Fix และปรับปรุง
// แก้ Bug: Math.random() * 26 (ไม่ใช่ 27)
const randomStringFixed = (length) => {
let result = '';
for (let i = 0; i < length; i++) {
result += String.fromCharCode(97 + Math.floor(Math.random() * 26));
}
return result;
};
// ใช้ Crypto-Secure Random (สำหรับ Security)
const randomStringSecure = (length) => {
const array = new Uint32Array(length);
crypto.getRandomValues(array);
return Array.from(array, x => String.fromCharCode(97 + (x % 26))).join('');
};
// ใช้ Base36 Encoding (สั้นกว่า)
const randomStringBase36 = (length) =>
[...Array(length)].map(() => Math.random().toString(36)[2]).join('');
// Custom Character Set
const randomStringCharset = (length, charset = 'abcdefghijklmnopqrstuvwxyz') =>
[...Array(length)].map(() => charset[Math.floor(Math.random() * charset.length)]).join('');
การประยุกต์ใช้
- Temporary Passwords / API Keys
- Session IDs / Tokens
- Unique Filenames
- Test Data Generation
- CAPTCHA Codes
ข้อควรระวังด้าน Security
- Math.random() ไม่ Cryptographically Secure - อย่าใช้สำหรับ Password, Token, Secret
- ใช้
crypto.getRandomValues()หรือcrypto.randomUUID()แทน - Entropy: 26^length ต้องเพียงพอสำหรับ Use Case
Best Practice สำหรับ Production
const generateSecureToken = (length = 32) => {
const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const bytes = new Uint32Array(length);
crypto.getRandomValues(bytes);
return Array.from(bytes, x => charset[x % charset.length]).join('');
};
// หรือใช้ UUID
const generateUUID = () => crypto.randomUUID();
// '123e4567-e89b-12d3-a456-426614174000'