Obscuring email address in JavaScript

Need to darken an email address with JavaScript? Here’s the secret. For what reason may you need to do it? A touch of security!

We have heaps of supporters at Ultimate Courses, and I like to see a dashboard imparted to my colleagues when new endorsers join. However, for security reasons, I obviously need to ensure their email addresses before our API sends them back. In this way, enter clouding!

What darkening permits us to do is take an email this way:

[email protected]

change it into this:


What I’m doing is supplanting the quantity of characters in the email with a reference bullet *.

In the first place, how about we make our capacity that acknowledges an email string:

const obscureEmail = (email) => {



Presently, we’ll use String.prototype.split to part the email by the @ image.

A string split returns an exhibit, and with present day ES6 highlights, we can infact effectively destructure the “name” before the @ image and “area” expansion:

const obscureEmail = (email) => {

const [name, domain] = email.split(‘@’);

console.log(name); // toddmotto

console.log(domain); // website.com


From here, we need to supplant the name with marks, however I need to keep the principal character as opposed to clouding everything.

To get the main character from name we could utilize substring or simply a snappy property query – as it’s more limited I will decide in favor of name[0].

We can then astutely utilize new Array(name.length) to build another cluster from the length of the string, which will give us an exhibit with unclear qualities (we don’t mind what’s in it, we will go along with it):

[undefined, undefined, undefined, undefined]

Proceeding onward, we can call new Array(name.length).join(‘*’) which will at that point join each of the 4 qualities and utilize 3 reference marks. Basically, in the event that you look over, every comma, will be supplanted by * a there are 4 things, there are 3 bullets.

At that point we can attach the area and we’re finished:

const obscureEmail = (email) => {

  const [name, domain] = email.split(‘@’);

  return `${name[0]}${new Array(name.length).join(‘*’)}@${domain}`;


const email = obscureEmail(‘[email protected]’);

console.log(email); // t********@website.com