I'm trying to write a function that will take the email of the user as a parameter and return the first part of the email, up to but not including the "@" symbol. Problem is I'm terrible with functions, and there's something wrong with this function but I'm not sure what it is. When I try and write the function to the page to see if it worked correctly, it keeps showing up undefined.
function emailUsername(emailAddress)
{
var userName = "";
for(var index = 0; index < emailAddress.length; index++)
{
var CharCode = emailAddress.charCodeAt(index);
if(CharCode = 64)
{
break;
}
else
{
userName += emailAddress.charAt(index);
return userName;
}
}
}
var email = new String(prompt("Enter your email address: ",""));
var write = emailUsername(email);
document.write(write);
I'm sure there are other ways to do it but I need to follow roughly this format of using a function to check what's before the "@" and using methods to find it out.
Solution 1: Using substring() function The substring() function in JavaScript can be used to get the text before the "@" symbol in an email address. This can be useful when you want to extract the username from an email address. We will also use the indexOf() function of Javascript to get the position of @.
Like this:
return emailAddress.substring(0, emailAddress.indexOf("@"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With