The getOnlyEmail
function extracts email addresses from a given text. If the optional multiple
parameter is set to true
, it returns an array with all the email addresses found. Otherwise, it returns only the first email address found as a string.
The function can be imported using ES6 syntax from the "multiform-validator" package:
import { getOnlyEmail } from 'multiform-validator';
Alternatively, you can import the function using CommonJS syntax with require
(Node.js):
const { getOnlyEmail } = require('multiform-validator');
The function takes two parameters:
text
(string) - The input text from which emails will be extracted.multiple
(optional boolean) - If set to true
, the function will return an array with all the email addresses found. If set to false
or not provided, it will return only the first email address found as a string.cleanDomain
(optional boolean | string[]) - Either a boolean value indicating whether to clean after default domains or an array of custom domains to clean after. Default is false
which means it won't clean the email addresses after default domains ['.br', '.io', '.pt', '.us', '.org', '.com'];. If set to true
, it will clean after default domains. If set to an array of strings, it will clean after the specified custom domains.repeatEmail
(optional boolean) - If set to false
, the function will remove duplicate emails from the output list. If set to true
or not provided, it will keep the duplicate emails in the output list.// Example 1 - Extracting multiple emails from the text
const result1 = getOnlyEmail(
"Entre em contato com a equipe: joao@empresa.com, maria@empresa.com, contato@empresa.com",
{ multiple: true },
);
console.log(result1);
// Output: ["joao@empresa.com", "maria@empresa.com", "contato@empresa.com"]
// Example 2 - Extracting the first email from the text
const result2 = getOnlyEmail(
"Vaga na asdlaod Mande seu email para fiawn@rdwah.com Sim aqui mesmo",
);
console.log(result2);
// Output: "fiawn@rdwah.com"
const result3 = getOnlyEmail(
"Vaga na asdlaod Mande seu email para fiawn@rdwah.comSim aqui asdasd@gmail.commesmo",
{ multiple: true, cleanDomain: true },
);
console.log(result3);
// Output: [ 'fiawn@rdwah.com', 'asdasd@gmail.com' ]
const result4 = getOnlyEmail(
"Vaga na asdlaod Mande seu email para fiawn@rdwah.comSim aqui asdasd@gmail.commesmo asdasd asd as fiawn@rdwah.com",
{ multiple: true, cleanDomain: true, repeatEmail: true },
);
console.log(result4);
// Output: [ 'fiawn@rdwah.com', 'asdasd@gmail.com', 'fiawn@rdwah.com' ]
If no email address is found in the input text, the function will return the string 'No email found'.