1. ## Generating random letters

I have the following script that generates a string of the letter "a" depending on the value in maxSize. Now I need to change this so the value of "a" in 'text = text + "a"' is a random value of a - z.

Can anyone advise how to do this.

// This function returns a string of length "maxSize" as pass by parameter
// that contain lots of "a"s. E.g. GetStringOfLength(5) = "aaaaa";

function GetStringOfLength(maxSize)
{
var i, text = "";
for(i = 0; i < maxSize; i++)
{
text = text + "a";
}
return text;
}

2. ## Re: Generating random letters

Hi Oompa

It looks like you're using JScript, so you can add a Math.random statement to your function, like this:

function GetStringOfLength(maxSize)
{
var i,text="";
//The below line generates a random number between 0 and the maxSize
var randNum= Math.floor(Math.random()*maxSize);
var randomLength = maxSize - randNum;
for (i=0;i<randomLength,i++)
{
text = text + "a";
}
return text;
}

There's a nice tutorial on the random method here:
http://www.pageresource.com/jscript/jrandom.htm

Hope this helps,
Nick

3. ## Re: Generating random letters

http://www.codehouse.com/javascript/tips/random_letter/

This gives you the following code That would replace your line:

text = text + "a";

with

text = text + String.fromCharCode(97 + Math.round(Math.random() * 25));

Where 97 = "a", and the rand will give you a value from 0 to 25.

I hope this helps,

4. ## Re: Generating random letters

Thanks guys.

Both worked fine, I replaced text = text + "a" with the follwing in two new scripts:

//Random number between 1 - 9
text = text + Math.round(9*Math.random())

//Random letter between a - z
text = text + String.fromCharCode(97 + Math.round(Math.random() * 25));

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•
BetaSoft Inc.
All times are GMT -8. The time now is 05:55 PM.