如何使用 javascript 从电子邮件地址中提取用户名? [英] How can I extract the user name from an email address using javascript?
本文介绍了如何使用 javascript 从电子邮件地址中提取用户名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定以下电子邮件地址——someone@example.com——我如何使用javascript从地址中提取某人?
Given the following email address -- someone@example.com -- how can I extract someone from the address using javascript?
谢谢.
推荐答案
Regular Expression with match
安全检查
var str="someone@example.com";
var nameMatch = str.match(/^([^@]*)@/);
var name = nameMatch ? nameMatch[1] : null;
写成一行
var name = str.match(/^([^@]*)@/)[1];
正则表达式替换
安全检查
var str="someone@example.com";
var nameReplace = str.replace(/@.*$/,"");
var name = nameReplace!==str ? nameReplace : null;
写成一行
var name = str.replace(/@.*$/,"");
拆分字符串
安全检查
var str="someone@example.com";
var nameParts = str.split("@");
var name = nameParts.length==2 ? nameParts[0] : null;
写成一行
var name = str.split("@")[0];
每个示例的性能测试
这篇关于如何使用 javascript 从电子邮件地址中提取用户名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文