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 »
10,640 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 »
10,640 Comments

@Elliot,

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


Apr 12, 2011 at 7:55 AM // reply »
12 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
InVision App - Prototyping Made Beautiful With Prototyping Tools Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
Feb 10, 2012 at 7:21 PM
jQuery AJAX Strips Script Tags And Inserts Them After Parent-Most Elements
Update! Instead of $(eval(options.insertAfter)).after(data['insertData']); I now use: var ajaxNode = document.createElement('span'); var parent = $(eval(options.insertAfter))[0].parentNode; ... read »
Feb 10, 2012 at 6:18 PM
jQuery AJAX Strips Script Tags And Inserts Them After Parent-Most Elements
encountered this same, what I consider, jQuery bug last week. I'm building a site in which I load some content via AJAX. This content contains Linkedin share button placeholders which Linkedin API ne ... read »
Feb 10, 2012 at 11:30 AM
Cross-Origin Resource Sharing (CORS) AJAX Requests Between jQuery And Node.js
After you understand the concepts here, this is an awesome cheatsheet for enabling CORS in just about anything http://enable-cors.org/ ... read »
JM
Feb 10, 2012 at 9:10 AM
My Safari Browser SQLite Database Hello World Example
@Amy, Here is a very good tutorial on how to use JOIN: http://www.sqltutorial.org/sqljoin-innerjoin.aspx ... read »
Feb 10, 2012 at 4:42 AM
Building A Twitter-Inspired RESTful API Architecture In ColdFusion
This is great, very useful Ben. I spotted a small typo in the api.cgm listing: <cfthrow type="Unauthroized" /> Cheers Stefan ... read »
Feb 9, 2012 at 10:35 PM
CFDirectory Filtering Uses Pipe Character For Multiple Filters (Thanks Steve Withington)
I was wondering if there would be a filter you could apply so that you got everything but what you included in the filter. As in show me all docs that are not a .pdf. ... read »
Feb 9, 2012 at 10:29 PM
Learning ColdFusion 9: Application-Specific Data Sources
@Ben, No offence, but if people were really wanting advanced features they would be using a platform like ASP.NET MVC. CFML is so structurally compromised as a tag-based scripting language that ... read »
Feb 9, 2012 at 10:03 PM
Subversion - Cleanup Failed To Process The Following Paths
@Leviaguirre, do you still have problems with this? ... read »