user4227915
user4227915

Reputation:

Regex, match text that starts with @, but don't take the @

I was learning regex at codecademy and in the last exercise I needed to create getDomainsOfEmails() function.

...and I got this:

function getDomainsOfEmails(text) {
    var domains = /@[a-z0-9-]+\.[a-z0-9]+/g;
    return text.match(domains);
}

But ideally the function should return the domains without the '@':

var emails = "";
emails += "[email protected] ";
emails += "[email protected] ";
emails += "[email protected] ";
console.log ( getDomainsOfEmails (emails));

I solved it with a loop:

function getDomainsOfEmails(text) {
    var domains = /@[a-z0-9_.]+\.[a-z0-9]+/g;
    var arr = text.match(domains);
    for (var i=0, l=arr.length; i<l; i++) {
        arr[i] = arr[i].substring(1);
    }
    return arr;
}

But I didn't like my approach, and reading the SO's Regex-wiki I found this instruction about pattern delimiters:

(?:pattern) doesn't capture match

So, I tried it:

function getDomainsOfEmails(text) {
    var domains = /(?:@)[a-z0-9-]+\.[a-z0-9]+/g;
    return text.match(domains);
}

But it continues returning the '@'.

What I did wrong?

Upvotes: 0

Views: 108

Answers (2)

RobertoNovelo
RobertoNovelo

Reputation: 3809

Use the x(?=y) rule that states "Matches 'x' only if 'x' is followed by 'y'. This is called a lookahead" using a * to allow more matches following @, and then get all a-z A-Z . - characters until a space /s is found.

var emails = "";
emails += "[email protected] ";
emails += "[email protected] ";
emails += "[email protected] ";

var re = /(?=@*)([a-zA-Z.-]+\s)/g;

console.log(re.exec(emails));

Upvotes: 0

hwnd
hwnd

Reputation: 70732

You can use a capturing group around the part of your pattern you want to retain, but you would need to use the exec() method in a loop, pushing the captured matches to an array.

Another way you can do this:

function getDomainsOfEmails(text) {
   var domains = /@[a-z0-9-]+\.[a-z0-9]+/g
   return text.match(domains).map(function(s) { return s.slice(1) })
}

eval.in

Upvotes: 2

Related Questions