"Trouble arises with the match() function in relation to email regex validation

After retrieving the HTML content from a website with my function, I am using String.prototype.match along with a regex rule to extract email addresses from that page. However, the issue is that I am receiving a line that matches the regex but does not contain the actual email address, and it includes all of the appended DOM elements.

My current challenges are:

  1. The regex is not correctly capturing the email part of mailto:xxxx.

  2. Unexpectedly, the entire DOM is being displayed in the console when I use console.log(matches[0]);

const websiteEmailRegex = 'mailto:([^\?]*)';

let HTML = document.documentElement.outerHTML;

let matches = HTML.match(websiteEmailRegex);
if (matches) {
    console.log('email', matches[0]);
}

Here is a snippet of what appears in the console:

mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="10797e767f5064716264716964717e6471633e7563">[email protected]</a>"> <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7c15121a133c081d0e081d05081d12081d0f52190f">[email protected]</a></a></p>
<p>No cogemos pedidos por mail.</p>


<p></p>
                </div><!-- .entry-content -->

                <footer class="entry-footer">
                                        </footer><!-- .entry-footer -->
        </div>
</article><!-- #post-## -->

                </main><!-- #main -->
        </div><!-- #primary -->

</div></div>
        <footer id="colophon" class="site-footer" role="contentinfo" itemscope="" itemtype="http://schema.org/WPFooter">

                <div class="container">

                            <div class="footer-t">
        <div class="row">
            <div class="three-cols">
                <div class="col">
                                    </div>
                <div class="col center">
                    <section class="widget widget_contact_form">
                                        </section>
                </div>
                <div class="col">
                                    </div>
            </div>
        </div>
    </div>
    <div class="site-info">
        <span>
        ©2020 <a href="http://tartaytantas.es/">Tartaytantas - Tartas y bizccochos a domicilio en Aravaca</a>.        </span>
        Bakes and Cakes | Desarrollado por        <a href="https://rarathemes.com/" rel="nofollow" target="_blank">
            Rara Theme        </a>
        Funciona gracias a <a href="https://wordpress.org/">WordPress.</a>

    </div><!-- .site-info -->

                </div>

        </footer><!-- #colophon -->
        <div class="overlay"></div>
        <a href="javascript:void(0);" class="btn-top"><span>Arriba</span></a>

        </div><!-- #acc-content -->
</div><!-- #page -->

<script type="text/javascript" src="https://secureservercdn.net/160.153.137.170/zm5.b57.myftpupload.com/wp-content/themes/bakes-and-cakes/js/owl.carousel.min.js

Answer №1

The regular expression pattern mailto:([^\?]*) will successfully match instances of mailto: followed by any characters that are not a question mark.

If your goal is to specifically capture all occurrences of mailto URLs within <a> tags, you may want to adjust your regex pattern to also include everything up until the closing quotation mark (" or ') of the HTML attribute:

const emailRegexPattern = 'mailto:([^\'\"]+)';

Check out this regex demonstration for more information

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

Unable to display icons using vuetify/mdi

When considering an Icon library, I decided to go with Vuetify not only for its ability to include icons but also for the other design advantages it offers. After npm installing @mdi/js and Vuetify in my existing project, here is the code snippet from my ...

What causes the source code of a website to change when accessed from various browsers?

When analyzing the source code of bartzmall.pk using various browsers, it reveals different classes being added to the html tag for each browser. For Firefox: <html class="firefox firefox53 otherClasses"> For Chrome: <html class="webkit chrome ...

Exiting the Protractor timeout setting for Safari WebDriver

While I have experience with unit tests using Karma, my office is now interested in integration tests, specifically to test cross-browser capabilities. Protractor seemed like the best option for this, so I began working on some basic dashboard tests. Howev ...

The function in jQuery that can be used to hide a <div> when clicked

I am facing a problem with my jQuery code that is supposed to remove/hide a specific div. Despite checking various examples, I can't seem to make it work properly. This issue arises in the context of jQuery on Drupal 7. The live site where this proble ...

JavaScript (Automatic) for a full-screen webpage display

I'm having trouble creating a webpage and setting it to fullscreen mode. Here's the JavaScript code I have: var elem = document.getElementById("fulscreen"); var fs = document.getElementById("body"); elem.onclick = function() { req = fs.webk ...

What is the method to trigger a function upon opening an anchor tag?

When a user opens a link in my React app, I need to send a post request with a payload to my server. My current strategy involves using the onClick and onAuxClick callbacks to handle the link click event. However, I have to filter out right-clicks because ...

Is there a way to retrieve the timestamp of a DOM change event when using MutationObserver for event tracking?

Currently, I am successfully using MutationObserver to monitor changes in the DOM. However, I would like to include a timestamp for each event. Unfortunately, there doesn't seem to be a timestamp property available in the MutationRecord. https://deve ...

Adding the <a> tag causes Superfish to malfunction

I've been struggling to get the latest Superfish menu code working with lists that include the <a> tag. I've double-checked everything, but it seems like I'm missing something obvious. Can anyone help me figure out what's wrong? ...

Working with dynamic checkbox values in VueJS 2

In my project using VueJS 2 and Vuetify, I am creating a subscription form. The form is dynamic and fetches all the preferences related to a subscription from the server. In the example below, the preferences shown are specifically for a digital magazine s ...

Organize express controller by breaking it up into multiple separate files

Recently, I've set up an express js controller file as follows The File Path: /controllers/usersController.js // Register User module.exports.register = function(req, res) { ... } // Login User module.exports.login = function(req, res) { ... } // ...

Managing errors with async/await in an Angular HttpClient function

I have been experimenting with an async/await pattern to manage a complex scenario that could potentially result in "callback hell" if approached differently. Below is a simplified version of the code. The actual implementation involves approximately 5 co ...

The transition property in CSS and JavaScript does not seem to be functioning properly in Firefox

Recently, I integrated a Slide in menu script on my website using a Slide in menu script. After following all the instructions provided, the menu started working flawlessly on Chrome and Safari browsers. However, my main goal was to make it function on Fir ...

What are the steps to apply an AngularJS filter for formatting values within an array?

While I have experience using angular filters for formatting primitive values like numbers into currency formats, I am now faced with the challenge of applying the same filtering to an array of values. For example: price = 1 prices = [1,2,3] If I were to ...

Encountering an issue when trying to retrieve the "createdAt" property in Cloud Code using the Parse Framework

I am working with Cloude Code to develop a more complex query, but I am having trouble accessing the automatically created "createdAt" property by Parse. Here is my code: Parse.Cloud.define("get_time", function(request, response) { var query = new Par ...

Troubleshooting: Vue JS failing to recognize new objects and properties in HTML

Within my Vue instance, I have a method named `loadPlannedAlerts` that performs an AJAX call to retrieve JSON data. This method is called during the `mounted` lifecycle hook of my Vue JS instance. The retrieved JSON object consists of key-value pairs struc ...

Using Typescript/JSX to assign a class instance by reference

Looking to access an object's property by reference? See the code snippet below; class Point{ x:number; y:number; constructor(x,y) { this.x=x; this.y=y; } } const a = { first: new Point(8,9), second: new Point(10,12) }; let someBoo ...

Prevent user input when an alert window is open

Users keep pressing the enter key multiple times when an alert box pops up, causing them to accidentally dismiss the message by hitting 'ok'. Is there a simple way to prevent key presses on alert windows and only allow mouse input? ...

What are the steps to integrate Material-UI Tabs with react-router?

I've been working on integrating Material-UI tabs with routing in my project. Although the routing is functioning well and displaying the selected tab, the smooth animation while navigating between tabs seems to be broken. How can I ensure that react ...

Tips for accessing payment details from a stripe paymentElement component in a React application

Here is a basic code snippet for setting up recurring payments in Stripe: await stripe ?.confirmSetup({ elements, confirmParams: { return_url: url, }, }) After browsing through the documentation and the internet, I have two unanswere ...

Unlocking Bootstrap variables in Vue development (using Vanilla Bootstrap)

What is the best way to customize or theme bootstrap? I have heard that using sass to override bootstrap variables is recommended, but how can I integrate this into the Vue webpack workflow? I tried searching online and found suggestions to edit the vue.c ...