Sepp Hofer Sepp Hofer - 1 year ago 162
Javascript Question

javascript extract email text-parts before and after

I need to extract an email from a string.
The desired output is an array containing the text part before the email,
the email,
and the text after the email.

selection = 'Integer lectus nisi, facilisis sit amet@blabla.test eleifend nec, pharetra ut augue.';

part[0] = 'Integer lectus nisi, facilisis sit ';
part[1] = 'amet@blabla.test';
part[2] = ' eleifend nec, pharetra ut augue.';

What i have so far is a function extracting the email but i also need the parts before and after.

function extractEmails(selection){
return selection.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);

$output = extractEmails(selection); //returns 'amet@blabla.test'

How can this be done? Thanks!

Answer Source

This code might help you:

    function extractEmails(selection){
        return selection.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);

    function parse(){
       var input = document.getElementById("input").innerText;
       var email = extractEmails(input);
       var subject = input.substring(0, input.indexOf(email));
       var content = input.substring(input.indexOf(email) + email.toString().length);

       // Print out filteredList
       var output = document.getElementById("output");
       output.innerText = `Subject: ${subject}\nEmail: ${email}\nContent: ${content}`;

<body onLoad="parse()">
    <div id="input">Integer lectus nisi, facilisis sit amet@blabla.test eleifend nec, pharetra ut augue.</div>

    <div id="output"></div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download