Search code examples
javascriptdomdata-extraction

How to extract substring from a String with different values in Javascript?


I've a paragraph that has a list of some emails, phone, and URL.

I want to extract all (600) emails, phone, and URL from that single string.

I tried to do that with substr in Javascript but I may be missing somewhere.

Here is an example of my sample data:

*Email:[email protected]
Url: www.example.com
Tel: +123-456-789
Email:[email protected]
Url: www.example.com
Tel: +123-456-789
Email:[email protected]
Url: www.example.com
Tel: +123-456-789
Email:[email protected]
Url: www.example.com
Tel: +123-456-789*

Please guide me with JavaScript.

var myEmail = [];
var ol = myS.substr((myS.indexOf("Email:")+1),(myS.indexOf('Url:')-2));
for(let i=0;i<600;i++){
   var ml = myS.substr((myS.indexOf(ol)+1),(myS.indexOf('Url:')-2));
console.log(ml);

}

Solution

  • const data = `*Email:[email protected]
    Url: www.example.com
    Tel: +123-456-789
    Email:[email protected]
    Url: www.example.com
    Tel: +123-456-789
    Email:[email protected]
    Url: www.example.com
    Tel: +123-456-789
    Email:[email protected]
    Url: www.example.com
    Tel: +123-456-789*`;
    
    const reEmails = /^\*?Email: ?(.*@.*\..*)\*?$/gm;
    const reTels = /^\*?Tel: ?(\+?\d*-?\d*-?\d*)\*?$/gm
    const reUrls = /^\*?Url: ?(www\..*\..*)\*?$/gm
    
    const emails = data.match(reEmails).map(m => m.replace(reEmails, '$1'));
    const tels = data.match(reTels).map(m => m.replace(reTels, '$1'));
    const urls = data.match(reUrls).map(m => m.replace(reUrls, '$1'));
    
    console.log('emails:', emails);
    console.log('tels:', tels);
    console.log('urls:', urls);