Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
191
rated 0 times [  197] [ 6]  / answers: 1 / hits: 58946  / 11 Years ago, thu, august 22, 2013, 12:00:00

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 = [email protected];


Will be just johdoe? I tried with split but it did not end well. thanks.


More From » javascript

 Answers
5
var email = "[email protected]";
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/rfc3696Page 5):



john@doe

"john@@".doe

"j@hn".d@e




Using RegExp:


Given the email value is already validated, String.prototype.match() can be than used to retrieve the desired name, domain:


String match:


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

Capturing Group:


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

To get both fragments in an Array, use String.prototype.split() to split the string at the last @ character:


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

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

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




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

[ // LIST OF VALID EMAILS:
`[email protected]`,
`john@[email protected]`,
`john@@[email protected]`,
`[email protected]@[email protected]`,
]
.forEach(email => {
const [name, domain] = getEmailFragments(email);
console.log(DOMAIN: %s NAME: %s , domain, name);
});




[#76232] Tuesday, August 20, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dustin

Total Points: 599
Total Questions: 105
Total Answers: 106

Location: Belarus
Member since Tue, Mar 14, 2023
1 Year ago
dustin questions
;