Generate random password string with requirements in javascript

A little more maintainable and secure approach.

An update to expand on what I meant and how it works.

  1. Secure. MDN is pretty explicit about the use of Math.random for anything related to security:

    Math.random() does not provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the window.crypto.getRandomValues() method.

    Looking at the can-i-use for getRandomValues in 2020 you probably don't need the msCrypto and Math.random fallback any more, unless you care about ancient browsers.

  2. Maintainable is mostly about the RegExp _pattern as an easy way to define what character classes you allow in the password. But also about the 3 things where each does its job: defines a pattern, gets a random byte as securely as possible, provides a public API to combine the two.

var Password = {
 
  _pattern : /[a-zA-Z0-9_\-\+\.]/,
  
  
  _getRandomByte : function()
  {
    // http://caniuse.com/#feat=getrandomvalues
    if(window.crypto && window.crypto.getRandomValues) 
    {
      var result = new Uint8Array(1);
      window.crypto.getRandomValues(result);
      return result[0];
    }
    else if(window.msCrypto && window.msCrypto.getRandomValues) 
    {
      var result = new Uint8Array(1);
      window.msCrypto.getRandomValues(result);
      return result[0];
    }
    else
    {
      return Math.floor(Math.random() * 256);
    }
  },
  
  generate : function(length)
  {
    return Array.apply(null, {'length': length})
      .map(function()
      {
        var result;
        while(true) 
        {
          result = String.fromCharCode(this._getRandomByte());
          if(this._pattern.test(result))
          {
            return result;
          }
        }        
      }, this)
      .join('');  
  }    
    
};
<input type='text' id='p'/><br/>
<input type='button' value ='generate' onclick='document.getElementById("p").value = Password.generate(16)'>

Forcing a fixed number of characters is a bad idea. It doesn't improve the quality of the password. Worse, it reduces the number of possible passwords, so that hacking by bruteforcing becomes easier.

To generate a random word consisting of alphanumeric characters, use:

var randomstring = Math.random().toString(36).slice(-8);

How does it work?

Math.random()                        // Generate random number, eg: 0.123456
             .toString(36)           // Convert  to base-36 : "0.4fzyo82mvyr"
                          .slice(-8);// Cut off last 8 characters : "yo82mvyr"

Documentation for the Number.prototype.toString and string.prototype.slice methods.