Ask Ben: Creating Large Random Strings In Javascript

Posted August 8, 2006 at 12:34 PM

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:

 Launch code in new window » Download code as text file »

  • 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:

 Launch code in new window » Download code as text file »

  • // 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:

 Launch code in new window » Download code as text file »

  • // 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:

 Launch code in new window » Download code as text file »

  • // 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.

Download Code Snippet ZIP File

Post Comment  |  Ask Ben  |  Permalink  |  Other Searches  |  Print Page



Learning ColdFusion 9 - ColdFusion 9 tutorials, samples, examples, demos

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 »
6,516 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 »
6,516 Comments

@Elliot,

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


Post Comment  |  Ask Ben

Recent Blog Comments
Nov 21, 2009 at 6:47 PM
Hal Helms - Real World Object Oriented Development, Sarasota - Day Five
@charlie griefer, Thank you.. ... read »
Nov 21, 2009 at 5:15 PM
Using ColdFusion Structures To Remove Duplicate List Values
@Jose Galdamez, Oh heh yeah I didn't paste the whole code. I should have defined the vars -- my bad. It's fixed thou. Thanks. ... read »
Nov 21, 2009 at 4:49 PM
Styling The ColdFusion 8 WriteToBrowser CFImage Output
Great work yet again Ben! Whilst I didn't use this whole code, I copied some of your regex code for a similar problem with the lack of an alt attribute and unescaped ampersands in CFIMAGE for Railo 3 ... read »
Nov 21, 2009 at 1:13 PM
My First ColdFusion Builder Extension - Encrypting And Decrypting CFM / CFC Files
@Ben, Because I am pedantic, I just want to make sure that everyone knows there is absolutely no encryption going on. There is only encoding and obfuscation. The cfencode tool only obfuscates your C ... read »
Nov 21, 2009 at 12:28 PM
Using ColdFusion Structures To Remove Duplicate List Values
@Jody I can't seem to get your code sample to work. If you are still having problems, try this code out and see if it gets you what you wanted. <!--- Comma delimited list with various duplicates ... read »
Nov 21, 2009 at 11:03 AM
Groovy Operator Overloading Does Not Work In The ColdFusion Context
Hi Ben, Thanks for this informative post. Now I am reading ur old posts too ... read »
Nov 21, 2009 at 10:56 AM
HostMySite.com Has The Best ColdFusion Hosting
@Mehul, Yes very nice people, however several downtimes per day which was not acceptable. Hence we had to move out. I am glad you are having good luck with them so far. ... read »