Naemy
Naemy

Reputation: 536

Regex that only works on browser tester

I've tested my regex on Regex testers and it worked, but I didn't get it to work on my code.

var mail = "[email protected]";
var regExp = new RegExp("@(.*?)\.");
document.write(regExp.exec(mail)) ;

I get this result :

@g,

I tried to add a backslash before the dot, and I got this :

@gmail.,gmail

I also wanted to remove the "@" and the "." from the email, so I tried to use " (?:@) ", but I didn't get it to work (on Regex testers).

It's my first time trying to use Regex, and I don't get it. Why is there a comma ?

Upvotes: 1

Views: 122

Answers (3)

jfriend00
jfriend00

Reputation: 707328

A couple things to do differently:

  1. You need to double escape your backslash in the string so that one backslash still remains for the RegExp constructor or switch to the /regex here/ syntax.
  2. If you want just the subgroup in the parens, you need to refer to that specific subgroup.

Here's the code:

var mail = "[email protected]";
console.log(mail.match(/@(.*?)\./)[1]);

Upvotes: 1

salih0vicX
salih0vicX

Reputation: 1373

Faster than regex:

var emailAddress = "[email protected]";
var array_email = emailAddress.split("@");​​
alert('Account: ' + array_email[0] +'; Domain: ' + array_email[1]);​​​​​​​​​​​​​​​​​​​​​​​​​​

Upvotes: 1

gdoron
gdoron

Reputation: 150253

You can use this regex to get the domain name:

/@(.+)\./

Live DEMO

Upvotes: 2

Related Questions