在“@”符号之前解析文本的电子邮件

时间:2010-11-22 17:53:10

标签: javascript

我正在尝试编写一个函数,将用户的电子邮件作为参数并返回电子邮件的第一部分,但不包括“@”符号。问题是我的功能很糟糕,这个功能有问题,但我不确定它是什么。当我尝试将该函数写入页面以查看它是否正常工作时,它会一直显示未定义。

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);

我确信还有其他方法可以做到,但我需要大致遵循这种使用函数的格式来检查“@”之前的内容并使用方法来查找它。

4 个答案:

答案 0 :(得分:33)

像这样:

return emailAddress.substring(0, emailAddress.indexOf("@"));

答案 1 :(得分:4)

function emailUsername(emailAddress) {
   return emailAddress.match(/^(.+)@/)[1];
}

答案 2 :(得分:0)

另一种可能性:

Private Sub btnSavecol_Click()
    Dim cancel As Integer

    If Me.ColName = "" Then
        MsgBox "You must enter a Colour Name."
        DoCmd.GoToControl "ColName"

        cancel = True
    Else
        If MsgBox("Are you sure you want to create new Colour?", vbYesNo) = vbNo Then
            cancel = True
        Else
            CurrentDb.Execute " INSERT INTO Colours (ColName) VALUES ('" & Me.ColName & "')"

            Me.ColName = ""

            DoCmd.Close

            If CurrentProject.AllForms("frmProductCreate").IsLoaded = False Then
                cancel = True
            Else
                Forms!frmproductCreate!ColourID.Requery
                'Forms!frmproductCreate!ColourID.SetFocus
                'Forms!frmproductCreate!ColourID.items.Count = -1
                'Forms!frmproductCreate!ColourID.Selected(Forms!frmproductCreate!ColourID.Count - 1) = False

                'YourListBox.SetFocus
                'YourListBox.ListIndex = YourListBox.ListCount - 1
                'YourListBox.Selected(YourListBox.ListCount - 1) = False
            End If

            If CurrentProject.AllForms("frmProductDetails").IsLoaded = False Then
                cancel = True
            Else
                Forms!frmproductDetails!ColourID.Requery
            End If
        End If
    End If
End Sub

这会将字符串在function emailUsername(emailAddress) { return emailAddress.split('@')[0] } 符号处切成两半,创建一个包含两个部分的数组,然后检索数组中的第一项,它将是@之前的部分。

答案 3 :(得分:0)

如果要确保它是电子邮件(正则表达式与真实电子邮件一样不容易),可以使用Masala Parser

std::vector<char> y(x.begin(),x.end());