2016-11-26 297 views
3

我想从一系列电子邮件地址中获取名字和姓氏。每个电子邮件地址都有一个模式。该模式是[email protected],但在某些情况下,它可能是[email protected]。主要观点是电子邮件中的名字和姓氏之间可能存在某些内容,但并非总是如此。 总是相同的主要模式是第一个字符串,直到第一个点始终是第一个名称,并且姓氏始终是最后一个字符系列,直到@ char从前一个DOT开始。 实例:从模式电子邮件地址提取名字和姓氏

[email protected] 第一个:查尔斯 最后:Bukowski的

[email protected] 第一个:查尔斯 最后:Bukowski的

charles.x .markus.bukowski @ company.com 第一名:charles last:bukowski

获得第一个名字很简单。我有以下变量:

var empmail = '[email protected]' 
var empname = empmail.substring(0, empmail.indexOf(".")); 

我无法找到出去姓的方式。

+0

MySQL有一个有用的功能叫做SUBSTRING_INDEX(),将解决你的问题选择SUBSTRING_INDEX( “ABCD”, - 1 )返回“d”这是一个JavaScript版本的[先前的StackOverFlow解决方案](http://stackoverflow.com/questions/3839944/javascript-equivalent-of-the-mysql-function-substring-index) – NCRANKSHAW

+1

可能的重复[使用Ms-SQL从电子邮件ID中提取用户名和用户标识](http://stackoverflow.com/questions/24 798098/extract-username-and-userid-from-e-mail-ids-using-ms-sql) –

回答

0

使用String.prototype.split()方法:

var empmail = '[email protected]' 

var fullName = empmail.split('@')[0].split('.'); 

var firstName = fullName[0]; 
var lastName = fullName[ fullName.length-1 ] 
+0

这真是太棒了!这是一个分裂的分裂。我没有想过这个。你能告诉我,[0]究竟是什么? – Vishera

+0

Split返回一个字符串数组。该表达式[[0])返回数组的第一个元素(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)。 –

1

使用String#match方法与正则表达式来获取名称。

var empmail = '[email protected]' 
 

 
var match = empmail.match(/^(\w+)\..*\.(\w+)@/); 
 

 
var empname = match[1]; 
 
var emplname = match[2]; 
 

 
console.log(
 
    empname, 
 
    emplname 
 
)

Regex explanation here


或者用String#lastIndexOf方法

var empmail = '[email protected]' 
 
var empname = empmail.substring(0, empmail.indexOf(".")); // get first name 
 

 
// get complete name part 
 
var namePart = empmail.substring(0, empmail.indexOf("@")); 
 
// get last name from name part 
 
var emplname = namePart.substring(namePart.lastIndexOf('.') + 1); 
 

 
console.log(
 
    empname, 
 
    emplname 
 
)


或使用String#splitArray#pop方法。

var empmail = '[email protected]' 
 
// split by `.` and get first element 
 
var empname = empmail.split('.')[0]; 
 

 
// split name part and get last element from array 
 
var emplname = empmail.split('@')[0].split('.').pop(); 
 

 
console.log(
 
    empname, 
 
    emplname 
 
)

0

你也可以用这种方法对于给定的电子邮件ID

var emailfirstname = a.slice(0,a.indexOf('@')).split('.')[0] 

var emailLastname = a.slice(0,a.indexOf('@')).split('.')[a.slice(0,a.indexOf('@')).split('.').length - 1] 
相关问题