0

I am doing exercises in javascript and i came across a problem. the user should choose the character length in the password however if i select 4 characters in the input I get 3. why?

my thought was to be useful to choose the number of characters and to generate a password as many characters as there are. where I am wrong I ask for help!

function generirajLozinku(pLength) {

  var keyListAlpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
    keyListInt = "123456789",
    keyListSpec = "",
    password = '@';
  var len = Math.ceil(pLength / 2); // mijenanjem ovog broja mijenja se duzina lozinke
  len = len - 1;
  var lenSpec = pLength - 2 * len;

  for (i = 0; i < len; i++) {
    password += keyListAlpha.charAt(Math.floor(Math.random() * keyListAlpha.length));
    password += keyListInt.charAt(Math.floor(Math.random() * keyListInt.length));
  }

  for (i = 0; i < lenSpec; i++)
    password += keyListSpec.charAt(Math.floor(Math.random() * keyListSpec.length));

  password = password.split('').sort(function() {
    return 0.5 - Math.random()
  }).join('');

  return password;
}



function myFunction() {
  var x = document.getElementById("num").value;

  document.getElementById("demo2").innerText = generirajLozinku(x);
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Document</title>

</head>

<body>

  <section>
    <div>
      <h1>Your strong password marker</h1>
      <p>Password length</p>
      <input type="number" name="izaberi boj karaktera!" id="num" min="4" max="10">
      <br>
      <button onclick="myFunction()">Generate</button>
      <p id="demo2">Your password</p>

    </div>
    <div>

    </div>


  </section>


</body>

</html>
t.niese
  • 39,256
  • 9
  • 74
  • 101
Sebweb
  • 5
  • 4

4 Answers4

0

The reason for your code not working is this is the last loop where you try to fill up the missing characters:

  for (i = 0; i < lenSpec; i++)
    password += keyListSpec.charAt(Math.floor(Math.random() * keyListSpec.length));

You choose a random character from keyListSpec, but you defined keyListSpec as keyListSpec = "", so there is nothing to choose from.

The design choice of your code is really strange. The passwords generated have a very predictable pattern, which will dramatically reduce possible combinations. The suffering of the characters in the password does not help there. In addition to that the sort(function() { return 0.5 - Math.random() }) is not a very good way of shuffling.

Also Math.random() is not a good choice when it comes to password generation. If you are looking for a password generator written in JavaScript you should take a look at e.g. Generate random password string with requirements in javascript in particular at this answer.

t.niese
  • 39,256
  • 9
  • 74
  • 101
0

It was not working for evens it seems, ie 4, 6, etc. The way you handled odds vs evens looked off. I did a simpler version for you.

function generirajLozinku(pLength) {

  var keyListAlpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789",
    password = '@';
  var len = pLength - 1;

  for (i = 0; i < len; i++) {
    password += keyListAlpha.charAt(Math.floor(Math.random() * keyListAlpha.length));
 
  }

  password = password.split('').sort(function() {
    return 0.5 - Math.random()
  }).join('');

  return password;


}

function myFunction() {
  var x = document.getElementById("num").value;

  document.getElementById("demo2").innerText = generirajLozinku(x);
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Document</title>

</head>

<body>

  <section>
    <div>
      <h1>Your strong password marker</h1>
      <p>Password length</p>
      <input type="number" name="izaberi boj karaktera!" id="num" min="4" max="10">
      <br>
      <button onclick="myFunction()">Generate</button>
      <p id="demo2">Your password</p>

    </div>
    <div>

    </div>


  </section>


</body>

</html>
Sprep
  • 528
  • 10
  • 18
  • 1
    As you already suggest a better version, then please don't use `return 0.5 - Math.random()` for suffering. This is a very bad technique. – t.niese Oct 29 '21 at 08:17
  • t.niese, you are right. It seems you already suggested that so will leave it as your suggestion. I just wanted to point out where he had the issue. – Sprep Oct 29 '21 at 08:24
0

Check your code and comment it. pLength = 4 because keyListSpec = "" so the follwing code

// keyListSpec is "", so keyListSpec.charAt always return ""
for (let i = 0; i < lenSpec; i++)
    password += keyListSpec.charAt(Math.floor(Math.random() * keyListSpec.length));

function generirajLozinku(pLength) {
    var keyListAlpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
    keyListInt = "123456789",
    keyListSpec = "",
    password = '@';
    var len = Math.ceil(pLength / 2); // mijenanjem ovog broja mijenja se duzina lozinke
    len = len - 1;                    
    var lenSpec = pLength - 2 * len;

    // if pLength = 4 , len is 1 and lenSpec is 2
    // here password is "@"

    for (let i = 0; i < len; i++) {
        password += keyListAlpha.charAt(Math.floor(Math.random() * keyListAlpha.length));
        password += keyListInt.charAt(Math.floor(Math.random() * keyListInt.length));
    }
    // if pLength = 4 , len is 1 and lenSpec is 2
    // here password length is 3 "@xx"

    console.log("keyListSpec", keyListSpec);
    // keyListSpec is "", so keyListSpec.charAt always return ""
    for (let i = 0; i < lenSpec; i++)
        password += keyListSpec.charAt(Math.floor(Math.random() * keyListSpec.length));      

    password = password.split('').sort(function() {
        return 0.5 - Math.random()
    }).join('');

    return password;
}
Jian Zhong
  • 451
  • 3
  • 10
-1

Update

@t.niese are right, if he say it is bad idea to shadowing the real problem. as i wrote in the first answer, some parts of your code seemed "strange" to me. As @Sprep also correctly pointed out, the handling of even and odd values.

Here then is the working code. Inspired by @Sprep answer. I just shortened it a bit.

function generirajLozinku(pLength) {
     var keyListAlpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789',
     password = '@';
     var len = pLength - 1;

     for (i = 0; i < len; i++) {
      password += keyListAlpha.charAt(Math.floor(Math.random() * keyListAlpha.length));
    }
    return password;
}

old answear

I already Some of your code is weird. but a quick and easy fix would be to insert this line at the return. return password.slice(0, len);

Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
  • Trying to fix a problem by shadowing it is always a really bad idea. Besides that the text in the question is `however if i select 4 characters in the input I get 3` to there is one missing. – t.niese Oct 29 '21 at 08:08
  • 1
    it doesn't work if I insert that piece of code – Sebweb Oct 29 '21 at 08:10
  • you are right. your code is not clear. because the task could be done with much less code. but to review your code is beyond the scope of this article. – Maik Lowrey Oct 29 '21 at 08:11