alex_andrea alex_andrea - 5 months ago 10
Javascript Question

How to generate an email clue/hint in this format (ex. j*****e@example.com) using javascript

I have a "forgot email" page in our MEAN app where I need to show an email clue/hint to the user if the details that the user provided is successfully verified.

Let's say the user have the following email:

janedoe@example.com
.

The hint should be displayed in the following format:
j*****e@example.com
.

I tried using
split()
and
replace()
and I'm able to produce a result in the following format:
*******@example.com
.

The issue right now is that the first and last character before the
@
symbol are also replaced which should not be the case.

I created a simple code to show my current solution below.



angular.module('app', []).controller('TestController', ['$scope', function($scope) {
var email = 'janedoe@example.com';
var emailParts = email.split('@');
$scope.emailClue = emailParts[0].replace(/./gi, '*') + '@' + emailParts[1];

console.log($scope.emailClue);
}])

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="TestController">
<p>Our records show your email address as {{ emailClue }}. Please use this email to log in.</p>
</div>





I would really appreciate any help. Thanks.

Answer

Try this edit of your code: it takes the first part of the email (the username), takes the first letter and last letter, turns the rest into asterisks, and then joins them back together again.

angular.module('app', []).controller('TestController', ['$scope', function($scope) {
  var email = 'janedoe@example.com';
  var emailParts = email.split('@');

  /* EDITED SECTION */
  var firstLetter = emailParts[0].substring(0, 1);
  var lastLetter = emailParts[0].substring(emailParts[0].length-1, emailParts[0].length);
  emailParts[0] = emailParts[0].substring(1,emailParts[0].length-1);
  $scope.emailClue = firstLetter + emailParts[0].replace(/./gi, '*') + lastLetter + '@' + emailParts[1];
  /* END EDITED SECTION */
  

  console.log($scope.emailClue);
}])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="TestController">
  <p>Our records show your email address as {{ emailClue }}. Please use this email to log in.</p>
</div>

Comments