# Ask Ben: Creating Large Random Strings In Javascript

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

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.

### Looking For a New Job?

25% of job board revenue is donated to Kiva. Loans that change lives - Find out more »

Aug 5, 2008 at 11:09 PM // reply »

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 »

@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 »

@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 »

@Elliot,

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

Apr 12, 2011 at 7:55 AM // reply »

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 »

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

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: bold   italic   code Remember my information Subscribe to comments Send me a copy of this comment
InVision App - Prototyping Made Beautiful With Prototyping Tools Recent Blog Comments
Mar 11, 2014 at 2:00 AM
ColdFusion, jQuery, And "AJAX" File Upload Demo
hey Ben Nadel thanks for this tutorial. i have downloaded your code also but no luck.. i am new to this so , can you explain me some thing about this cf prefix ? ... read »
Mar 10, 2014 at 8:24 PM
Nested Views, Routing, And Deep Linking With AngularJS
@Steven, the action property is not something from AngularJS but rather part of the concept that Ben is describing in his blogpost here. it is a custom added property, which is read by the requestCo ... read »
Mar 10, 2014 at 2:03 PM
Nested Views, Routing, And Deep Linking With AngularJS
Where is the angular documentation for 'action:' it is not here: http://docs.angularjs.org/api/ngRoute/provider/ \$routeProvider Thanks. ... read »
Mar 10, 2014 at 12:06 PM
Using Track-By With ngRepeat In AngularJS 1.2
I was hoping that this will work with pagination using ng-repeat. My use case scenario is that I have an images object. images[0] = [im1,im2,im3] // First Page images[1] = [im4, im5, im6] // Second ... read »
Mar 9, 2014 at 6:11 PM
For Better Security Use HtmlEditFormat() In Conjunction With JSStringFormat() In ColdFusion
It looks like htmleditformat() will be deprecated in CF 11 https://wikidocs.adobe.com/wiki/display/coldfusionen/New +in+ColdFusion ... read »
Mar 9, 2014 at 10:55 AM
\$.stop() vs. \$.finish() In jQuery Animations
Nice feature! Thanks for sharing. :) Good for when you are making a 100% AJAX controlled site. ... read »
Mar 9, 2014 at 12:26 AM
Experimenting With Multiple Class Inheritance In Javascript
@bigboomshakala, Hi, I am want present so solution for multiple prototypical inheritance, but some restrictions. Please follow the link: http://arto8.site11.com/ArtoJS/multi-inheritance-prototype.ph ... read »
Mar 8, 2014 at 5:21 PM
Thoroughly Document Your Use Of ColdFusion's CFHTMLHead Tag
hi Ben, how can we mention our own custom tags instead of using HTML tags in coldfusion? kindly revert with an example. ... read »