Home > Software design >  Run RegEx Over Array and Return New Values in New Array
Run RegEx Over Array and Return New Values in New Array

Time:09-30

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]]

CodePudding user response:

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);

CodePudding user response:

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);

  • Related