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

Viewed 95

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:info@abc.com
Url: www.example.com
Tel: +123-456-789
Email:info@abc.com
Url: www.example.com
Tel: +123-456-789
Email:info@abc.com
Url: www.example.com
Tel: +123-456-789
Email:info@abc.com
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);

}
2 Answers

const data = `*Email:info@abc.com
Url: www.example.com
Tel: +123-456-789
Email:info@abc.com
Url: www.example.com
Tel: +123-456-789
Email:info@abc.com
Url: www.example.com
Tel: +123-456-789
Email:info@abc.com
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);

There is a simple solution if the format doesn't change to much.

Let's separate 'words' with regexp

const email = `*Email:info@abc.com
Url: www.example.com
Tel: +123-456-789
Email:info@abc.com
Url: www.example.com
Tel: +123-456-789
Email:info@abc.com
Url: www.example.com
Tel: +123-456-789
Email:info@abc.com
Url: www.example.com
Tel: +123-456-789*`;

const matches = email.match(/[^ :\n]*/g);
console.log(matches);

Now we can filter asking for '@' to be present

const results = matches.filter( e => e.indexOf('@') !== -1 );
console.log(results);
Related