Skip to main content
Ben Nadel at Angular 2 Master Class (New York, NY) with: Matthew Kim
Ben Nadel at Angular 2 Master Class (New York, NY) with: Matthew Kim ( @iamakimmer )

Ask Ben: Creating Large Random Strings In Javascript

By on

How can I go about creating a very large random string in Javascript?

Creating random text is just a matter of concatenating a given number of randomly chosen characters. There are two methods that jump to mind: choosing a character based on an ASCII value and choosing a character from a list of valid characters.

Both of these methods are going to involve the selection of a random integer. While Javascript does provide a method for returning a random number, that number is a large floating point number between 0 and 1. Let's create our own RandRange() method to mimic the sweet functionality provided by ColdFusion:

function RandRange( intFrom, intTo, intSeed ){
	// Make sure that we have integers.
	intFrom = Math.floor( intFrom );
	intTo = Math.floor( intTo );

	// Return the random number.
	return(
		Math.floor(
			intFrom +
			(
				(intTo - intFrom + 1) *

				// Seed the random number if a value was passed.
				Math.random(
					(intSeed != null) ? intSeed : 0
					)
			))
		);
}

A quick note about seeding a random number. Computers cannot really make random numbers. They can only appear to make random numbers. To help this facade, you have the option to seed the random number generator. By passing in different seeds to the random() method of the Math object, it helps to ensure that the numbers returned are more random. In the function above, you can pass a optional third argument that will be passed to the random() method.

To demonstrate, if you wanted to get a random number between 1 and 100, you could do either of the following:

// Get value with no seed.
var intValue = RandRange( 1, 100 );

// Get value with seed passed in (342).
var intValue = RandRange( 1, 100, 342 );

Ok, so let's go over the different methods for creating that string, starting with the use of ASCII values. As you might know, all characters have an equivalent ASCII value. For instance, a space character " " is represented by the ASCII value 32. To see the basic ASCII table, go to http://www.asciitable.com.

Given that, we can pick random characters based on ranges of ASCII numbers. If you look on the above table, you will see that ASCII values between 33 and 126 all produce visible characters. We will use this range to create the large random text:

// Define local variables.
var intI = 0;
var strLargeText = "";
var intValue = 0;

// Loop over number of characters in string.
for (intI = 0 ; intI < 10000 ; intI++){

	// Get a random value between 33 and 126. We are going
	// to use these to pick characters out of the ascii
	// table.
	intValue = RandRange( 33, 126, intI );

	// Append a character that is randomly chosen
	strLargeText += String.fromCharCode( intValue );

}

// Alert the ramdomly created string.
alert( strLargeText );

Here, we are creating a 10,000 character long string that consists only of characters between ASCII values 33 and 126. Part of what makes this so easy is the String.fromCharCode() method. From the example, you can see that this method of the String object takes an ASCII value and returns the character representation. For each iteration, we are getting that random character and appending it to the growing large string.

Notice that when we call RandRange(), we are passing in the iteration index as the seed value for the Math.random() method call. This just helps make the numbers appear more random.

If you don't want to choose from a range of ASCII values, you can choose from a list of given characters. Let's say you wanted to create a string that only had hexidecimal character values (0-9 and A-F). You could do this in a similar fashion:

// Define local variables.
var intI = 0;
var strLargeText = "";
var intValue = 0;
var arrCharacters = ( "0123456789ABCDEF" ).split();

// Loop over number of characters in string.
for (intI = 0 ; intI < 10000 ; intI++){

	// Get a random value between 0 and the length of the
	// character list.
	intValue = RandRange( 0, (arrCharacters.length - 1), intI );

	// Append a character that is randomly chosen
	strLargeText += arrCharacters[ intValue ];

}

// Alert the randomly created string.
alert( strLargeText );

In this example, we are using an array of characters. The string "0123456789ABCDEF" is being split up into an array, with a single letter at each index. Then, as we loop through the 10,000 iterations, we pick a random index of that character array and append the given character.

And there you have it. String concatenation is fairly slow, but even with 10,000 iterations it was able to perform on my computer is mere milliseconds.

Want to use code from this post? Check out the license.

Reader Comments

2 Comments

Thank you for this example, it helped me a lot!

But in your last example, there is one thing wrong, making that not working properly. It should be var arrCharacters = ( "0123456789ABCDEF" ).split( "" ); instead of var arrCharacters = ( "0123456789ABCDEF" ).split();.

15,663 Comments

@Elliot,

Good catch, although, did you try it without the empty string? I only ask because I usually copy and paste my code directly out of my test file. Either way, it should probably be there. Thanks.

2 Comments

@Ben,

I did try it without the quotes, it only repeated 0123456789ABCDEF instead of creating a random string. If it worked without the quotes, maybe it's because of the browser, i'm using Firefox 3.

14 Comments

Hi Ben,

That split function should indeed be:

Split("") and NOT Split()

In Firefox, without the quotes it creates a very large and not very random number despite the variables.

I believe in love. I believe in compassion. I believe in human rights. I believe that we can afford to give more of these gifts to the world around us because it costs us nothing to be decent and kind and understanding. And, I want you to know that when you land on this site, you are accepted for who you are, no matter how you identify, what truths you live, or whatever kind of goofy shit makes you feel alive! Rock on with your bad self!
Ben Nadel