Search code examples
javascriptjquery

Show first 3 letters of email and hide rest of letters before @


I'm trying to make a function that shows the first 3 letters of an email and then hide the rest of the letters before the @.

My email could be: [email protected]
What i would like it to look like: Ton********@stackoverflow.com

This is my best attempt so far, but i cant seem to find out how make the rest.

function hideemail(target) {
  var email = $(target).html();
  var hiddenEmail = "";
  for (i = 0; i < email.length; i++) {
    if (i > 2) {
      hiddenEmail += "*";
    } else {
      hiddenEmail += email[i];
    }
  }
  console.log(hiddenEmail)
}

hideemail(".email")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="email">[email protected]</div>


Solution

  • You need to check for the @ symbol aswell.

    Hence the condition becomes if (i > 2 && i< email.indexOf("@") ) {

    function hideemail(target) {
      var email = $(target).html();
      var hiddenEmail = "";
      for (i = 0; i < email.length; i++) {
        if (i > 2 && i< email.indexOf("@") ) {
          hiddenEmail += "*";
        } else {
          hiddenEmail += email[i];
        }
      }
      console.log(hiddenEmail)
    }
    
    hideemail(".email")
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="email">[email protected]</div>