tags:

views:

209

answers:

1
function randomString( len ) {
  // A random string of length 'len' made up of alphanumerics.
  var out = '';
  for (var i=0; i<len; i++) {
   var random_key = 48 + Math.floor(Math.random()*42); //0-9,a-z
   out += String.fromCharCode( random_key );
  }
  window.alert(out);
  return out;
}

As far as I can tell the result of String.fromCharCode is system and/or browser dependent. All the workarounds I've seen are for when you are actually capturing keycodes, not generating them. Is there a more reliable way to do this (like converting from ASCII codes?).

+2  A: 

var random_key = 48 + Math.floor(Math.random()*42); //0-9,a-z

The code and the comment doesn't correspond. The characters that may be created is in the range 0-9, :, ;, <, =, >, ?, @, and A-Z.

The character codes in this range is in the ASCII character set, so they are the same for all commonly used western character sets. The fromCharCode method should use the character set that you have specified for the page, but in the range that you are using that doesn't matter.

Make the range seven smaller, and add 39 if it's not a digit to get 0-9 and a-z:

function randomString(len) {
   // A random string of length 'len' made up of alphanumerics.
   var out = '';
   for (var i=0; i<len; i++) {
      var random_key = 48 + Math.floor(Math.random() * 36);
      if (random_key > 57) random_key += 39;
      out += String.fromCharCode(random_key);
   }
   window.alert(out);
   return out;
}
Guffa
That implies this table is wrong: http://www.cambiaresearch.com/c4/702b8cd1-e5b0-42e6-83ac-25f0306e3e25/Javascript-Char-Codes-Key-Codes.aspx
SpliFF
The table is for key codes, not character codes. You use it for example to determine the pressed key in the keydown event. Notice also that there is a gap in the table between 57 and 65.
Guffa