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;
})();
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly