Generate random string in JavaScript
May 23, 2009 19:46:01 Last update: May 23, 2009 19:49:46
This topic comes up once in a while: I need to generate a random string in JavaScript to get around browser (IE) cacheing.
- Method 1 (not really random, but a new value every millisecond):
function randomString() { return '' + new Date().getTime(); }
- Method 2 (generate a random alpha-numerical string):
function randomString(length) { var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split(''); if (! length) { length = Math.floor(Math.random() * chars.length); } var str = ''; for (var i = 0; i < length; i++) { str += chars[Math.floor(Math.random() * chars.length)]; } return str; } // generate a random string of random length randomString(); // generate a random string of length 8 randomString(8);
1 comment 