Ask Ben: Creating Large Random Strings In Javascript

Posted August 8, 2006 at 12:34 PM by Ben Nadel

Tags: Javascript / DHTML, Ask Ben

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.



Reader Comments

Aug 5, 2008 at 11:09 PM // reply »
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();.


Aug 6, 2008 at 8:23 AM // reply »
11,246 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.


Aug 6, 2008 at 8:58 AM // reply »
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.


Aug 6, 2008 at 9:15 AM // reply »
11,246 Comments

@Elliot,

No worries. I think using the empty string, "", is more proper anyway. Good catch.


Apr 12, 2011 at 7:55 AM // reply »
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.


Aug 14, 2011 at 4:22 PM // reply »
1 Comments

Math.random() doesn't actually take a parameter; the function is seeded by the time.

If you want to pass a seed to random (and you don't, the way you're presenting it here), you need to write your own PRNG. There's one liked here, which does accept a seed value: http://stackoverflow.com/questions/521295/javascript-random-seeds


Post A Comment

Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.

Please review the following issues:

Author Name:


Author Email:

Author Website:

Comment:

Supported HTML tags for formatting: <strong>bold</strong>   <em>italic</em>   <code>code</code>







  • Help Wanted - Find Your Next ColdFusion Job
Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
May 23, 2013 at 6:06 PM
The Girl Who Broke My Heart, And Made Me A Better Person
Good day,ladies and gentle men, my name is Dr AMADI the great spell caster in Africa, i have help so many people for different kind of problems,who say there is no solution to problems on earth, that ... read »
May 23, 2013 at 4:26 PM
ColdFusion QueryAppend( qOne, qTwo )
@Heather, Glad people are still getting value out of this! ... read »
May 23, 2013 at 3:49 PM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
@WebManWalking, I meant the code at the bottom (not the video). I did try to experiment with an intermediary variable, like: value = users.id[ i ]; arrayContains( userIDs, value ); ... but t ... read »
May 23, 2013 at 11:06 AM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
@Ben, Are you talking about As Number: YES As String: YES As Java: YES? If so, that's with 3 different ways of referencing the constant 1, not users.id[1]. Query object references(*) are what seem ... read »
May 23, 2013 at 9:55 AM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
@Dan, According to the CF Admin, I'm running Java "1.6.0_45". As far as the DB column, in the database it's an INT. I'll see if I can dig into what CF sees it as. @WebManWalking, But h ... read »
May 23, 2013 at 9:49 AM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
@Ben, I think the problem is that we're used to loose typing in ColdFusion, like JavaScript. If a value is a number but it's needed in an expression to be a string, noooo problem. I've encountered ... read »
May 23, 2013 at 9:47 AM
ColdFusion QueryAppend( qOne, qTwo )
You rock! Thank you, thank you, thank you!!! ... read »
May 23, 2013 at 5:19 AM
Ask Ben: Print Part Of A Web Page With jQuery
How to print also the background color of table cells and table lines ... read »
InVision App - Prototyping Made Beautiful With Prototyping Tools