Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to generate random charactor/number?

Status
Not open for further replies.

alan123

MIS
Oct 17, 2002
149
US
I'd like to know how to use javascript to generate random string (which includes 0-9,A-z, and has fixed length 10)?
 
hi alan123,

here's one way:

[tt]
function getRndStr() {
var chars = "abcdefghijklmnopqrstuvwxyz0123456789";
var sRes = "";
for (x = 0; x < 10; x++) {
// get next char
nextChar = chars.charAt(Math.round(Math.random() * chars.length));
// randomly make uppercase
if (Math.round(Math.random()) == 1) nextChar = nextChar.toUpperCase();
sRes += nextChar;
}
return sRes;
}
[/tt]
=========================================================
if (!succeed) try();
-jeff
 
oops - the script lets strings < 10 chars pass...here's a new version:
[tt]
function getRndStr() {
var chars = &quot;abcdefghijklmnopqrstuvwxyz0123456789&quot;;
var sRes = &quot;&quot;;
for (x = 0; x < 10; x++) {
// get next char
nextChar = chars.charAt(Math.round(Math.random() * (chars.length - 1)));
// randomly make uppercase
if (Math.round(Math.random()) == 1) nextChar = nextChar.toUpperCase();
sRes += nextChar;
}

if (sRes.length != 10) getRndStr();
else return sRes;
}
[/tt]
=========================================================
if (!succeed) try();
-jeff
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top