简体   繁体   English

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

[英]Parsing an email for the text before the “@” symbol

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. 我确信还有其他方法可以做到,但我需要大致遵循这种格式使用函数检查“@”之前的内容并使用方法找出它。

像这样:

return emailAddress.substring(0, emailAddress.indexOf("@"));
function emailUsername(emailAddress) {
   return emailAddress.match(/^(.+)@/)[1];
}

Another possibility: 另一种可能性

function emailUsername(emailAddress) {
  return emailAddress.split('@')[0]
}

This splits the string in half at the @ symbol, creating an array with the two parts and then retrieves the first item in the array, which will be the part before the @ . 这将字符串在@符号处分成两半,创建一个包含两个部分的数组,然后检索数组中的第一个项目,它将是@之前的部分。

If you want to be sure that it's an email (regex are not easy wiith real emails), you can use Masala Parser 如果你想确定它是一封电子邮件(正则表达不是真正的电子邮件),你可以使用Masala Parser

import {C,Streams} from '@masala/parser'

function email() {

    const illegalCharSet1 = ' @\u00A0\n\t';
    const illegalCharSet2 = illegalCharSet1+'.';

    return C.charNotIn(illegalCharSet1).rep() // repeat( anyCharacter not illegal)
        .map(chars => ({start:chars.join()})) // will be kept by `.first()`
        .then(C.char('@'))
        .then(C.charNotIn(illegalCharSet2).rep())
        .then(C.char('.'))
        .then(C.charNotIn(illegalCharSet2).rep())
        .first(); // keep only the first  element of the tuple

}

let val = email().val('nicolas@masala.oss');
console.log(val); // {start:'nicolas')


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM