Reputation: 991
I have a string like this:
Francesco Renga <[email protected]>
I need to extract only the email, i.e. [email protected].
How can I do this in nodejs/javascript in "elegant" way?
Upvotes: 4
Views: 16981
Reputation: 145
function getEmailFromText(text){
const has = text.includes("@");
const left = text.split("@")[0];
const right = text.split("@")[1];
const email = has ? `${left.split(" ")[(left.split(" ").length-1)]}@${right.split(" ")[0]}` : "";
const re_email = email.match(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g);
return re_email ? re_email[0] : "";
}
console.log(getEmailFromText("Contact me on: [email protected] other other..."));
Upvotes: 0
Reputation: 535
Here's a simple code showing how extract the unique list of emails address using JavaScript :
let emaillst = string .match(/([a-zA-Z0-9._+-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
if (emaillst === null) {
// no Email Address Found
} else {
const uniqueEmail = Array.from(new Set(emaillst));
const finaluniqueEmail = [];
for(let i=0; i<=uniqueEmail.length; i++){
let characterIs = String(uniqueEmail[i]).charAt(String(uniqueEmail[i]).length - 1)
if(characterIs==='.'){
finaluniqueEmail.push(String(uniqueEmail[i].slice(0, -1)))
}else{
finaluniqueEmail.push(uniqueEmail[i]);
}
}
emaillst = finaluniqueEmail.join('\n').toLowerCase();
console.log(matches[1]);
See the Live Demo of email address extractor online
Features
Upvotes: 4
Reputation: 3627
Using regex, if your string pattern is always Some text<email>
or Some text<email>, Some text<email> <email>
you can use this simple one <(.*?)>
Other solution
Use positive lookahead : [^<]+(?=>)
, here is a snippet and a demo
var text = "Francesco Renga <[email protected]>, Marty McFly <[email protected]> Marty McFly <[email protected]> <[email protected]>";
var re = /[^< ]+(?=>)/g;
text.match(re).forEach(function(email) {
console.log(email);
});
Explanation
[^<]+
match anything but a <
between one and unlimited times
(?=>)
followed by a >
Simple and does not require any group.
Upvotes: 7
Reputation: 4027
Here's a simple example showing how to use regex in JavaScript :
var string = "Francesco Renga <[email protected]>"; // Your string containing
var regex = /<(.*)>/g; // The actual regex
var matches = regex.exec(string);
console.log(matches[1]);
Here's the decomposition of the regex /<(.*)>/
:
/
and /
are mandatory to define a regex<
and >
simply matches the two <
and >
in your string()
parenthesis "capture" what you're looking for. Here, they get the mail address inside..*
: .
means "any character", and *
means "any number of times. Combined, it means "any character any number of times", and that is inside <
and >
, which correspond to the place where the mail is.Upvotes: 4