Hi, I would like to generate the random string using javascript? How can I achieve it?
Any length of string would work but if possible I would like to have a random string of 6 characters.
There are multiple ways to generate random string in javascript:
1. Using Math.Random
Math.random().toString(36).substring(6); // .substring(6) for 6 characters
2. Creating a function
function randomString() {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var string_length = 8;
var randomstring = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
}
document.randform.randomfield.value = randomstring;
}
You can call the above function like
<input type="button" value="Generate Random String" onClick="randomString();">
You can generate random string using following code
(function() {
var randomString = function(length) {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for(var i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
// call function random string with length
var rand= randomString(10);
// insert random string to the field
var elem = document.getElementById("randomString").value = rand;
})();
You can simply use the code below to generate random string in JS
let random = (Math.random() + 1).toString(36).substring(6);
console.log(random);
in the above code, we have length of "6" characters, you can change length to "7" or "5" depending on your random string requirement.
In the above code, you can expect to see duplicate after 50,000 unique random string.
OR
If required you can also generate UUID, based on time-stamp, which can be unique.
function generateUUIDUsingMathRandom() {
var d = new Date().getTime();//Timestamp
var d2 = (performance && performance.now && (performance.now()*1000)) || 0;//Time in microseconds since page-load or 0 if unsupported
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16;//random number between 0 and 16
if(d > 0){//Use timestamp until depleted
r = (d + r)%16 | 0;
d = Math.floor(d/16);
} else {//Use microseconds since page-load if supported
r = (d2 + r)%16 | 0;
d2 = Math.floor(d2/16);
}
return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
}
Generating GUID/UUID using Javascript (Various ways)
Thanks.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly