Have you ever needed to come up with a random string of characters say for a password? Maybe you’re looking for a random string of characters for an oauth 1.0 nonce. Maybe you’re in a job interview and you’re asked to generate a random alpha numeric string.
Whatever the case, we’re going to look at generating a random string of characters of any given length using JavaScript.
If you’ve been keeping up with my open source work, you’ve probably seen a nonce function I’ve made for use with oauth 1.0a providers.
A nonce via Wikipedia:
An arbitrary number used only once in a cryptographic communication.
Here is one way to create such a 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;
}
This code was actually taken from a popular Stack Overflow example.
So in case you’re not familiar how the code works. We first define a string of all the allowed characters in our final randomized string. We then loop until a given length which will represent the string size. In this loop we will look at the allowed character string as a kind of array (character by character) and randomly choose an index of the array. This then allows us a random string.
Knowing how to create a random string is good for oauth nonce’s, strong passwords, and interview questions for software engineering phone screenings. Good to know and easy to do.
A video version of this article can be seen below.