Skip to content
Advertisement

WIX Velo – Extracting Domain from User Email – Regex Issue

I am trying to retrieve the domain of my site users in order to assign them specific organisation based privileges.

If their email address is email@example.com, I want to extract example. If it’s email@ex.ample.com I want to extract ex.ample

The regex I have is (?<=@)[^.].[^.](?=.)

But I’m struggling to integrate this into the code. My code as follows:

$w.onReady(async function () {
 let userEmail = await memberData.loginEmail;
    retrieveTeamFromEmail(userEmail);
    $w('#userAccountSetupIntroText').text = ("Let's set up your account. We have your company as " +
        userEmail + ".nnTell us a little more about yourself.");
})

function retrieveTeamFromEmail(userEmail) {
 return userEmail
        .replace(?<=@)[^.]*.[^.]*(?=.);
}

I’m getting an error at .replace:

.replace error

What am I doing wrong?

Advertisement

Answer

Instead of using replace, you can match the part using a capture group.

[^s@]@([^s@]+).[a-z]{2,}

The pattern matches:

  • [^s@]@ Match any char except a whitspace char or @
  • ( Capture group 1
    • [^s@]+ Match 1+ times any char except a whitspace char or @
  • ) Close group 1
  • .[a-z]{2,} Match a dot (note to escape the dot) and 2 or more chars a-z

Regex demo

const pattern = /[^s@]@([^s@]+).[a-z]{2,}/;

function retrieveTeamFromEmail(s) {
  const m = s.match(/[^s@]@([^s@]+).[a-z]{2,}/, s);
  return m ? m[1] : s;
}
[
  "email@example.com",
  "email@ex.ample.com",
  "test"
].forEach(s =>
  console.log(retrieveTeamFromEmail(s))
)
Advertisement