Home > Software engineering >  How to check if a running strings is equal to a target string
How to check if a running strings is equal to a target string

Time:08-29

Suppose I let the user enter a passcode that must match a set passcode.

let password = '12345';
let userInput = '';

Suppose the user enters 123 sequentially, so 1 then 2 then 3. The first 2 characters were correct, thus this function would return true, but when the 3 is entered, the function should return false. One way I thought of implementing this function was to use substr, but this would return true if the user input has any portion of the password correct, not just the first to last ones. Any help would be appreciated!

CodePudding user response:

Like Jonas Wilms said you just need to check it with client type value by using lenght and check it with the password.

const input = document.querySelector('input');
const password = '12345';
input.addEventListener('keyup', function(e) {
  let vLength = this.value.length;
  console.log(password.slice(0, vLength) == this.value);
});
<p>Password = <b>12345</b></p>
<input type="text">

  • Related