2

I am trying to resetting password in react Js. I need to display that email is sent to their email Id. I don't want to display their whole email instead I want to replace some characters with *. For example, someone has an email [email protected] so I want to replace some random character with * ie tes***[email protected]. How could I do that in javascript?? My code:

let a = [email protected]
let c = a.split('@');
let b = c[0].slice(0,-3)+'***'+'@'+c[1];

but it is not efficient way.How to do efficiently??

suppose if i have [email protected] then it should display t**[email protected] and if [email protected] it should be like a*[email protected].

8
  • "but it is not efficient way." Why not? Commented Jul 9, 2018 at 11:36
  • i want to slice from second last not from last one Commented Jul 9, 2018 at 11:37
  • How to slice string from the end in JavaScript? Commented Jul 9, 2018 at 11:38
  • Try regex replace Commented Jul 9, 2018 at 11:38
  • 1
    I suggest you give some examples of input and expected output. When you say you have an issue for short names you don't tell us what you want to happen. Update the question with a few email address examples and what you want to get back. Commented Jul 9, 2018 at 11:53

2 Answers 2

2

use this :

 var input = "[email protected]";

function callme(){
    var a = input.split("@"); 
    var b = a[0];
    var newstr = "";
    for(var i in b){
     if(i>2 && i<b.length-1)newstr += "*";
     else newstr += b[i];
    }
    console.log(newstr +"@"+ a[1]);
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="callme()">click me</button>

Sign up to request clarification or add additional context in comments.

3 Comments

Wait till the OP clarifies what they want. This won't obfuscate any email addresses with the name part < 4 characters long.
ya you are right. I wrote this code as per output! :)
jQuery is included because…?
2

You've got the start: split into parts and apply an algorithm to the first part to replace some characters, then join the bits again.

The following replaces part of the first part based on a formula that always leaves the last character and replaces at least one of the leading characters. It replaces more of the leading characters as the string gets longer.

Tweak the multipliers that generate the startIndex and endIndex values to replace more or fewer characters.

function mungeEmailAddress(s) {
  var i = s.indexOf('@');
  var startIndex = i * .2 | 0;
  var endIndex   = i * .9 | 0;
  return s.slice(0, startIndex) +
         s.slice(startIndex, endIndex).replace(/./g, '*') +
         s.slice(endIndex);
}

// Testing...
for (var s='', t = '@foo.com', i=97; i<110; i++) {
  s += String.fromCharCode(i);
  console.log(s + t + ' => ' + mungeEmailAddress(s + t));
}
 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.