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:
JavaScript
x
12
12
1
$w.onReady(async function () {
2
let userEmail = await memberData.loginEmail;
3
retrieveTeamFromEmail(userEmail);
4
$w('#userAccountSetupIntroText').text = ("Let's set up your account. We have your company as " +
5
userEmail + ".nnTell us a little more about yourself.");
6
})
7
8
function retrieveTeamFromEmail(userEmail) {
9
return userEmail
10
.replace(?<=@)[^.]*.[^.]*(?=.);
11
}
12
I’m getting an error at .replace:
What am I doing wrong?
Advertisement
Answer
Instead of using replace, you can match the part using a capture group.
JavaScript
1
2
1
[^s@]@([^s@]+).[a-z]{2,}
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
JavaScript
1
13
13
1
const pattern = /[^s@]@([^s@]+).[a-z]{2,}/;
2
3
function retrieveTeamFromEmail(s) {
4
const m = s.match(/[^s@]@([^s@]+).[a-z]{2,}/, s);
5
return m ? m[1] : s;
6
}
7
[
8
"email@example.com",
9
"email@ex.ample.com",
10
"test"
11
].forEach(s =>
12
console.log(retrieveTeamFromEmail(s))
13
)