December 30, 2024

Answer to JavaScript Password Exercise Q7

 

/*
This function will accept a string as its argument. If the string is a single
space character, the function will return true,
else it returns false
*/
function isSpace(str)
{
  if (str == ' ')
  {
    return true;
  }
  else
  {
    return false;
  }
}
// ************ main program ************
var password , numOfChars, i , isOK;
password = window.prompt('Enter a password, no spaces please!' , '');
numOfChars = password.length;
/*
initialise i - this will reference the index of each character in the string
*/
i= 0;
/*
initialise a flag, this will be used as part of the condition to
start the loop and stop it if a space is detected
*/
isOK = true;
while ((i < numOfChars)&& isOK)
{
  //now call the function
  if (isSpace(password.charAt(i)))
  {
    isOK = false; // the loop will terminate
  }
  else
  {
    i = i + 1;
  }
}
//now check the flag
if (isOK)
{
  window.alert('Valid');
}
else
{
  window.alert('Invalid, contains a space!');
}

Notes:

  • The function is written at the top of the program.
  • It uses the reserved word return to answer with the required Boolean value
  • There is no need to declare the local variable (using var) representing the argument to the function, in this case str. Just make sure that it is not a reserved word!

 

Back « JavaScript password exercises

 

 

 

 

 

 

 

 

Up to top of page