Javascript: How to quickly create a random string of a defined Character set in one line of JS code

During my writing on a regular expression tutorial, I came up with random number generator which is useful for some testing cases, as well as in situations where a simple encryption algorithm is useful.

There are at least four modes of operation for such a generator thinkable:
  1. random bytes e.g. random binary output

  2. random text e.g. ASCII printable character subset of values (Dec 32-126), click here for a complete table 

  3. variable, random output-length of text

  4. increasing or decreasing bias toward a given character with increasing text length


Listed below are the variables needed for these four cases, and further down the respective implementation.
  1. STRLEN, any integer defining the text length

  2. STRINGLENGTH replaced by (Math.random()*MAXLENGTH).toFixed()
    Math.random() returns any 16bit float ranging from 1 as the upper boundary to 0.01 as the lower boundary. Some web- references cite from 1 to 0. However such a function would be much less useful, and is in fact not implemented. To get any random number within a given range just add the lower bound to it, whilst substracting it from the upperbound. Setting the upper boundary is always easy: it is simply the number you multiply with. It's default lower boundary will be 1% of that. For example 1) this means 0, 1 and 2 will never be encountered.
    (Math.random()*UPPERBOUND-LOWERBOUND).toFixed()+LOWERBOUND
    Note: Likewise, a random text length between an upper and lower bound could be set

  3. Refer to 2).  Likewise, a random text length between an upper and lower bound could be set

  4. Refer to 2). The upperboundary is decremented by the running variable i, and the lower boundary incremented by i. The then resulting number is used to generate a character.



LihatTutupKomentar