wolftooth
wolftooth

Reputation: 27

How to show first four characters in password and display the asterisk next to it?

I am trying to display the first four characters and show the asterisk using namespacing from a password input field:

users.page.passChar = userInput => {
    let emptyStr = "";
    if (userInput) {
        emptyStr = userInput.substring(3);
        emptyStr.replace();
    }
    return emptyStr;
}

Upvotes: 0

Views: 1021

Answers (3)

Paul
Paul

Reputation: 36319

So, I assume you're looking for 'abc123' to display 'abc1**', based on your described functionality.

Given that, you'll want your function to look like this:

function passDisplay(userInput) {
  let result = '';
  if(userInput) {
    result = userInput.substring(0,4);
    if(userInput.length > 3) {
      result += Array(userInput.length - 4).fill('*').join('');
    }
  }
  return result;
}

Upvotes: 0

SamVK
SamVK

Reputation: 3395

One option using reduce:

const passChar = userInput => (
    [...userInput].reduce((input, char, i) => `${input}${(i > 3) ? '*' : char }`, '')
);

console.log(passChar('password'));

Upvotes: 1

gotnull
gotnull

Reputation: 27214

If I'm understanding your question properly you want to replace asterisks to the end of the string and only display the first four characters?

This should be a good start:

function passDisplay(userInput) {
    let emptyStr = "";
    if (userInput) {
        emptyStr = userInput.substring(0, 4);
        if (userInput.length > 3) {
           emptyStr += Array(userInput.length - 4).fill('*').join('');
        }
    }
    return emptyStr;
}
console.log(passDisplay("hunter2"));

Upvotes: 2

Related Questions