Tips for pulling out a specific section of text from a string using various values in JavaScript

I have a block of text containing a mix of emails, phone numbers, and URLs that I need to extract individually.

I attempted to use a substring method in JavaScript to achieve this, but I seem to be encountering some challenges.

Below is a snippet of the data I am working with:

*Email:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="31585f575e715053521f525e5c">[email protected]</a>
Url: www.example.com
Tel: +123-456-789
Email:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="523b3c343d123330317c313d3f">[email protected]</a>
Url: www.example.com
Tel: +123-456-789
Email:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="422b2c242d022320216c212d2f">[email protected]</a>
Url: www.example.com
Tel: +123-456-789
Email:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e881868e87a8898a8bc68b8785">[email protected]</a>
Url: www.example.com
Tel: +123-456-789*

I am looking for assistance in extracting this data using JavaScript.

var myEmails = [];
var data = myString.substr((myString.indexOf("Email:")+1),(myString.indexOf('Url:')-2));
for(let i=0;i<600;i++){
   var extracted = myString.substr((myString.indexOf(data)+1),(myString.indexOf('Url:')-2));
console.log(extracted);

}

Answer №1

const details = `*Email:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f990979f96b9989b9ad79a9694">[email protected]</a>
Url: www.example.com
Tel: +123-456-789
Email:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="026b6c646d426360612c616d6f">[email protected]</a>
Url: www.example.com
Tel: +123-456-789
Email:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="70191e161f301112135e131f1d">[email protected]</a>
Url: www.example.com
Tel: +123-456-789
Email:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="650c0b030a250407064b060a08">[email protected]</a>
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 extractedEmails = details.match(reEmails).map(e => e.replace(reEmails, '$1'));
const extractedTels = details.match(reTels).map(t => t.replace(reTels, '$1'));
const extractedUrls = details.match(reUrls).map(u => u.replace(reUrls, '$1'));

console.log('extracted emails:', extractedEmails);
console.log('extracted tels:', extractedTels);
console.log('extracted urls:', extractedUrls);

Answer №2

If the format remains relatively consistent, there is a straightforward solution available.

We can use regular expressions to separate 'words'.

const email = `*Email:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b7ded9d1d8f7d6d5d499d4d8da">[email protected]</a>
Url: www.example.com
Tel: +123-456-789
Email:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c3aaada5ac83a2a1a0eda0acae">[email protected]</a>
Url: www.example.com
Tel: +123-456-789
Email:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cba2a5ada48baaa9a8e5a8a4a6">[email protected]</a>
Url: www.example.com
Tel: +123-456-789
Email:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="472e292128072625246924282a">[email protected]</a>
Url: www.example.com
Tel: +123-456-789*`;

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

Next, we can filter the results by checking for the presence of '@'.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the world of Django: Using model formsets with the power

I am struggling to use Ajax for submitting my zipped formsets. The code functions flawlessly without Ajax, but as soon as I try to incorporate Ajax, I encounter a ValidationError: [u'ManagementForm data is missing or has been tampered with'] Thi ...

unable to access stored locations in XML file using JavaScript

I am attempting to retrieve a saved location from a database using JavaScript to read from an XML file. My goal is to add markers to a map based on these saved locations. Below is the XML code, can you identify any issues with my method of reading the XML? ...

What are the advantages of using the CRUD coding style with Redux?

Seeking guidance on the best coding style for a single page application regarding the use of React Redux For instance, consider a standard CRUD page where data is presented in a table with a pop-up modal form. The table's data comes from server-side ...

Everything seems to be functioning properly on the local server, but once the media files or players (mp3 and mp4) are uploaded, the background fails to work entirely

function playMusic() { var songs = [ "pump.mp3", "ybwm.mp3", "bb.mp3", ]; var randomIndex = Math.floor(Math.random() * songs.length); var selectedSong = songs[randomIndex]; var audio = new Audio(selecte ...

Issues with displaying ngAnimate animations

For the past 10 hours, I've been attempting to get my animations to function properly. It seems that they only work when I include the animate.css stylesheet and use the "animated classname". However, when I try to create custom entrance and exit anim ...

Issue identified: Multer is unable to read the path property of req.file as it is undefined

I recently started working with node.js and wanted to create a simple REST Api with the ability to upload files. I decided to use multer from npm for file uploading and POSTMAN to send post requests. However, I encountered an error when trying to upload a ...

Prisma generate: encountering issues resolving the dependency tree with Prisma, Postgresql, and NextJS integration

Every time I execute prisma generate, the following error is displayed: Prisma schema loaded from prisma/schema.prisma npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/ema ...

The phantom stdout for Node 4.2.0 is showing an error with code NETWORK_ERR: XMLHttpRequest Exception 101. This error indicates that a network error

Executing the code below in node 4.2.0, it is triggered within a scheduled node cron job rather than through the terminal. The website being 'requested' is . module.exports.dynamicRequest = function(url, callback) { var makeDynamicRequest = fu ...

How come only the final element is being displayed from an array in JavaScript, rather than all of the elements present

I am facing an issue while attempting to extract specific information from a JSON data and create a new array with key-value pairs. However, instead of getting all the elements, it only returns the last one. Here is my current code snippet: const input = ...

Loop through the AJAX response containing JSON data

Need assistance in extracting specific information from each hotel key and its rates within this JSON structure using JavaScript: [ { "auditData": { "processTime": "1545", "timestamp": "2016-04-08 04:33:17.145", ...

What is the best way to add the current date to a database?

code: <?php session_start(); if(isset($_POST['enq'])) { extract($_POST); $query = mysqli_query($link, "SELECT * FROM enquires2 WHERE email = '".$email. "'"); if(mysqli_num_rows($query) > 0) { echo '<script&g ...

How can I implement two dropdowns in jquery?

One of my dropdown menus is currently utilizing this code to fetch the selected value: $(document).on('change','#DropDown1',function() { var value1 = $(this).children("option:selected").val(); var data = {"key": value1}; ...

The ajax success error function does not trigger in jQuery

Hey, check out my code below: <html> <head> <script src="http://code.jquery.com/jquery-1.8.0.min.js"> </script> </head> <body> <form id="foo"> <label for="bar">A bar</label> <input id ...

Encountering a situation where an empty object is received while attempting to send a

While using Postman to make a request to the API I created for Social Media Application that involves following and followers functionality, I noticed that I am receiving an empty object: {}. However, upon inspection, everything seems to be correct on my e ...

Adding the state of an object to an existing array of objects using the useState

My goal is to create an array of objects structured like this [{},{},{}] The state variable is constructed as shown below: this.state:{...some states, parsed:[{}]} Each object is obtained from IPFS using an async function: IPFSREADER = ele ...

having trouble compiling a react js file with webpack

One of my files, app.js, contains the following code snippet: handlePageClick = (data) => { let selected = data.selected; let offset = Math.ceil(selected * this.props.perPage); this.setState({offset: offset}, () => { this.setStat ...

Is the key to achieving optimal client interactions within a client layout, while still maintaining its role as a server component, truly possible?

My current challenge involves managing modals opening and closing with server components instead of client components. In the past, I used to lift the state up to my Layout for client components: export default function Layout({ children }) { const [showP ...

What is the procedure to change a matter body's isStatic property to false in matter.js upon pressing a key?

During my recent project, I encountered a challenge in trying to set the isStatic property of a Matter Body in matter.js to false when a key is pressed. if (keyIsPressed(UP_ARROW)) { this.body.isStatic(false) } Could you provide guidance on the correct ...

Maintaining the position of the screen as you type in information that is located outside of the container

I am encountering an issue with the input/text-area element in absolute position extending halfway outside the container. The screen position seems to follow the caret as I type, but I'd prefer to keep writing and have part of the text hidden beyond t ...

Javascript Callback function not working as expected

I'm attempting to include an anonymous callback function in my code. I know it might seem a bit messy. By typing into the intro section, it triggers the animation using the .typed method with specific parameters. What I'm struggling to do is imp ...