[Vuejs]-Issue grabbing all emails from DOM string with match and regex

3👍

Because you’re using the RegExp constructor rather than a regex literal, the forward slashes and i at the end are getting interpreted as characters to match, and the backslashes are getting "eaten" by JavaScript’s string escaping. Here’s a simplified example:

const regexFromConstructor = new RegExp("/a\s+/i")
// evaluates to /\/s+\//i (matches 1 forward slash, 1 "a", 1+ "s"es, another forward slash, and finally 1 "i")

const regexFromLiteral = /a\s+/i
// matches 1 "a" followed by 1 or more whitespace characters, case insensitive

You can solve this by using a regex literal (delimited by forward slashes) instead:

const emailRegex = /([\s]*)([_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*([ ]+|)@([ ]+|)([a-zA-Z0-9-]+\.)+([a-zA-Z]{2,}))([\s]*)/gi;

0👍

Your regex is fine, you just need to construct the RegExp as a RegExp literal, that is, without quotes around it ":

var bodyHTML = '<header><div><a href="mailto:mymail@gmail.com"></a></div></header><a href="mailto:othermail@hotmail.com"></a>';

var emailRegex = new RegExp(/([\s]*)([_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*([ ]+|)@([ ]+|)([a-zA-Z0-9-]+\.)+([a-zA-Z]{2,}))([\s]*)/i, "g");
var results = bodyHTML.match(emailRegex);

console.log(results);

Leave a comment