Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing an email for the text before the "@" symbol

Tags:

javascript

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.

like image 541
Greener Avatar asked Nov 22 '10 17:11

Greener


People also ask

How do you put a string before an email?

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 @.


1 Answers

Like this:

return emailAddress.substring(0, emailAddress.indexOf("@"));
like image 139
SLaks Avatar answered Sep 23 '22 15:09

SLaks