How to detect a mail with native js

Detecting a mail link (mailto:) with native JavaScript can be done using the following methods:

Method 1: Using the href attribute

You can use the href attribute to check if the link is a mailto link. Here's an example:

const link = document.querySelector('a[href^="mailto:"]');
if (link) {
  console.log('Mail link detected!');
}

This code selects all <a> elements with an href attribute that starts with "mailto:". If a match is found, it logs a message to the console.

Method 2: Using a regular expression

You can use a regular expression to match the href attribute and detect mailto links. Here's an example:

const links = document.querySelectorAll('a[href]');
links.forEach((link) => {
  if (/^mailto:/i.test(link.href)) {
    console.log('Mail link detected!');
  }
});

This code selects all <a> elements with an href attribute and loops through them. It uses a regular expression to test if the href attribute starts with "mailto:". If a match is found, it logs a message to the console.

Method 3: Using the mailto protocol

You can also detect mailto links by checking if the href attribute contains the mailto protocol. Here's an example:

const links = document.querySelectorAll('a[href]');
links.forEach((link) => {
  if (link.href.includes('mailto')) {
    console.log('Mail link detected!');
  }
});

This code selects all <a> elements with an href attribute and loops through them. It checks if the href attribute includes the string "mailto". If a match is found, it logs a message to the console.

These methods can be used to detect mailto links in your JavaScript code. You can modify them to suit your specific use case.