0

I have an array of email addresses:

var emails = ['[email protected]', '[email protected]', '[email protected]']

I have a regular expressions to strip the last name from the emails:

var re = /(?<=[.]).*(?=[\@])/g; //Strips last name from email address.

I am trying to strip the last name and create a new array with those so it would look like:

[last, lst, name]

Here is the code I have tried, but it is not parsing out the last name at all and is just printing out the first and last email address. Any ideas on how I can achieve this? Thanks!

function onEdit() {
var re = /(?<=[.]).*(?=[\@])/g;
var emails = ['[email protected]', '[email protected]', '[email protected]']
const matchVal = emails.filter(value => re.test(value));
Logger.log(matchVal);
}

//Result of above function
//[[email protected], [email protected]]

2 Answers 2

3

You should be mapping over the emails and then getting the first match:

const re = /(?<=[.]).*(?=[\@])/g;
const emails = ['[email protected]', '[email protected]', '[email protected]']
const matchVal = emails.map(value => value.match(re)[0]);
console.log(matchVal);

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

Comments

0

Assuming there are only single email addresses per array entry, you can also get the desired values by splitting on @, check if you get back 2 parts

Then split the first part on a dot and then return the last value of that split.

const emails = [
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  'hello'
];
const result = emails.map(s => {
  const parts = s.split("@");
  return parts.length === 2 ? parts[0].split(".").pop() : s;
});
console.log(result);

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.