With javascript, how do we remove the @gmail.com or @aol.com from a string so that what only remains is the name? 

```
var string = "johndoe@yahoo.com";

```

Will be just "johdoe"? I tried with split but it did not end well. thanks.
['https://Stackoverflow.com/questions/18371339', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2522342/']
```
var email = "john.doe@example.com";
var name   = email.substring(0, email.lastIndexOf("@"));
var domain = email.substring(email.lastIndexOf("@") +1);

console.log( name );   // john.doe
console.log( domain ); // example.com

```

The above will also work for ***valid* names** containing `@` ([tools.ietf.org/html/rfc3696](https://www.rfc-editor.org/rfc/rfc3696)*Page 5*):

> 
> john@doe  
> 
> "john@@".doe  
> 
> "j@hn".d@e
> 
> 
> 

* [String.prototype.substring()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring)
* [String.prototype.lastIndexOf()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf)

Using RegExp:
-------------

Given the email value is [*already* validated](https://stackoverflow.com/questions/46155/how-to-validate-an-email-address-in-javascript), [String.prototype.match()](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/match) can be than used to retrieve the desired name, domain:

#### **String match:**

```js
const name   = email.match(/^.+(?=@)/)[0];    
const domain = email.match(/(?<=.+@)[^@]+$/)[0]; 

```

#### **Capturing Group:**

```js
const name   = email.match(/(.+)@/)[1];    
const domain = email.match(/.+@(.+)/)[1];

```

To get **both fragments** in an Array, use [String.prototype.split(](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split)) to split the string at the last `@` character:

```js
const [name, domain] = email.split(/(?<=^.+)@(?=[^@]+$)/);
console.log(name, domain);

```

or simply with `/@(?=[^@]*$)/`.  

Here's an example that uses a reusable function `getEmailFragments( String )`

```js
const getEmailFragments = (email) => email.split(/@(?=[^@]*$)/);

[ // LIST OF VALID EMAILS:
  `info@example.com`,
  `john@doe@example.com`,
  `"john@@".doe@example.com`,
  `"j@hn".d@e@example.com`,
]
.forEach(email => {
  const [name, domain] = getEmailFragments(email);
  console.log("DOMAIN: %s NAME: %s ", domain, name);
});
```
This simple regex will do the needful.  

`/^.*(?=@)/g`.

Example:

```
"johndoe@yahoo.com".match(/^.*(?=@)/g); // returns Array [ "johndoe" ]

```