Javascript 使用javascript拆分名字和姓氏
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12340789/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Split First name and Last name using javascript
提问by Subin
I have a user with a name Paul Steve Panakkal. It's a long name it won't fit to the div container. So is there anyway to split first name and lastname from it using javascript or jquery.
我有一个名为Paul Steve Panakkal的用户。这是一个长名称,它不适合 div 容器。那么无论如何使用javascript或jquery从中拆分名字和姓氏。
The name is got from PHP into a variable in JavaScript. This is then splitted using JS.
该名称是从 PHP 获取到 JavaScript 中的一个变量。然后使用 JS 进行拆分。
回答by Danil Speransky
You should use the String.prototype.split()
method:
您应该使用以下String.prototype.split()
方法:
'Paul Steve Panakkal'.split(' '); // returns ["Paul", "Steve", "Panakkal"]
You can use it this way:
你可以这样使用它:
'Paul Steve Panakkal'.split(' ').slice(0, -1).join(' '); // returns "Paul Steve"
'Paul Steve Panakkal'.split(' ').slice(-1).join(' '); // returns "Panakkal"
So in common:
所以共同点:
var firstName = fullName.split(' ').slice(0, -1).join(' ');
var lastName = fullName.split(' ').slice(-1).join(' ');
回答by David says reinstate Monica
Yes:
是的:
var fullName = "Paul Steve Panakkal".split(' '),
firstName = fullName[0],
lastName = fullName[fullName.length - 1];
References:
参考:
回答by abuduba
I think, it's time to get started with regular expressions :)
我想,是时候开始使用正则表达式了 :)
"Paul Steve Panakkal".split(/(\s).+\s/).join("") // "Paul Panakkal"
回答by EliuX
In Spanish it can be tricky because you may have a second optional name and even complex surnames like "del Bosque" or "de la Hoya", vowels with accent marks and the ?. The following javascript is capabable of parsing a full spanish name, having in count you are writting it respecting the upper and lower cases. It will return a json giving you
在西班牙语中,这可能很棘手,因为您可能有第二个可选名称,甚至可能有复杂的姓氏,如“del Bosque”或“de la Hoya”、带重音符号的元音和? . 下面的 javascript 能够解析一个完整的西班牙语名称,算上你正在编写它尊重大写和小写。它会返回一个 json 给你
- name: 1 or 2 main names
- lastName: the main lastname
- secondLastName: The second lastname
- 名称: 1 或 2 个主要名称
- lastName: 主要姓氏
- secondLastName: 第二个姓氏
The code is:
代码是:
function parseName(input) {
var fullName = input || "";
var result = {};
if (fullName.length > 0) {
var nameTokens = fullName.match(/[A-Zá-ú?ü][a-zá-ú?ü]+|([aeodlsz]+\s+)+[A-Zá-ú?ü][a-zá-ú?ü]+/g) || [];
if (nameTokens.length > 3) {
result.name = nameTokens.slice(0, 2).join(' ');
} else {
result.name = nameTokens.slice(0, 1).join(' ');
}
if (nameTokens.length > 2) {
result.lastName = nameTokens.slice(-2, -1).join(' ');
result.secondLastName = nameTokens.slice(-1).join(' ');
} else {
result.lastName = nameTokens.slice(-1).join(' ');
result.secondLastName = "";
}
}
return result;
}
The surnames are required if you are going to specify a second name. Try it out with:
如果您要指定第二个名字,则需要姓氏。试试看:
- Eliecer Hernández Garbey
- Oscar de la Hoya
- José Julian Martí Pérez
- Manuel de Céspedes del Castillo
- Calixto García í?iguez
- 埃利塞·埃尔南德斯·加贝
- 奥斯卡·德拉霍亚
- 何塞·朱利安·马蒂·佩雷斯
- 曼努埃尔·德·塞斯佩德斯·德尔·卡斯蒂略
- Calixto García í?iguez
Even try out a complex one like
甚至尝试一个复杂的像
- María de la Caridad del Bosque y Loynáz
- María de la Caridad del Bosque y Loynáz
Comment your experiences with it.
评论你对它的体验。
回答by Akash Jain
I tried below code and it works cool for me
我尝试了下面的代码,它对我来说很酷
var full_name = 'xyz abc pqr';
var name = full_name.split(' ');
var first_name = name[0];
var last_name = full_name.substring(name[0].length.trim());
In above example:
在上面的例子中:
(1)
(1)
If full_name = 'xyz abc pqr';
first_name = "xyz";
last_name = "abc pqr";
(2)
(2)
If `full_name = "abc"`:
Then first_name = "abc";
and last_name = "";
回答by blak3r
Extended version of Speransky Danil's answer which handles the case where the supplied string has only one word in it.
Speransky Danil 的答案的扩展版本,它处理所提供的字符串中只有一个单词的情况。
/**
* Gets the first name, technically gets all words leading up to the last
* Example: "Blake Robertson" --> "Blake"
* Example: "Blake Andrew Robertson" --> "Blake Andrew"
* Example: "Blake" --> "Blake"
* @param str
* @returns {*}
*/
exports.getFirstName = function(str) {
var arr = str.split(' ');
if( arr.length === 1 ) {
return arr[0];
}
return arr.slice(0, -1).join(' '); // returns "Paul Steve"
}
/**
* Gets the last name (e.g. the last word in the supplied string)
* Example: "Blake Robertson" --> "Robertson"
* Example: "Blake Andrew Robertson" --> "Robertson"
* Example: "Blake" --> "<None>"
* @param str
* @param {string} [ifNone] optional default value if there is not last name, defaults to "<None>"
* @returns {string}
*/
exports.getLastName = function(str, ifNone) {
var arr = str.split(' ');
if(arr.length === 1) {
return ifNone || "<None>";
}
return arr.slice(-1).join(' ');
}
回答by Visual Micro
if you assume the last word is the last name and a single word name is also a last name then ...
如果您假设最后一个单词是姓氏,而单个单词的名称也是姓氏,那么...
var items = theName.split(' '),
lastName = items[items.length-1],
firstName = "";
for (var i = 0; i < items.length - 1; i++) {
if (i > 0) {
firstName += ' ';
}
firstName += items[i];
}
回答by Yanir Calisar
Use this code:
使用此代码:
You'll need to change the line: splitFullName("firstName","lastName","fullName");
and make sure it includes the right field IDs from your form.
您需要更改行:splitFullName("firstName","lastName","fullName");
并确保它包含表单中正确的字段 ID。
function splitFullName(a,b,c){
String.prototype.capitalize = function(){
return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
};
document.getElementById(c).oninput=function(){
fullName = document.getElementById(c).value;
if((fullName.match(/ /g) || []).length ===0 || fullName.substring(fullName.indexOf(" ")+1,fullName.length) === ""){
first = fullName.capitalize();;
last = "null";
}else if(fullName.substring(0,fullName.indexOf(" ")).indexOf(".")>-1){
first = fullName.substring(0,fullName.indexOf(" ")).capitalize() + " " + fullName.substring(fullName.indexOf(" ")+1,fullName.length).substring(0,fullName.substring(fullName.indexOf(" ")+1,fullName.length).indexOf(" ")).capitalize();
last = fullName.substring(first.length +1,fullName.length).capitalize();
}else{
first = fullName.substring(0,fullName.indexOf(" ")).capitalize();
last = fullName.substring(fullName.indexOf(" ")+1,fullName.length).capitalize();
}
document.getElementById(a).value = first;
document.getElementById(b).value = last;
};
//Initial Values
if(document.getElementById(c).value.length === 0){
first = document.getElementById(a).value.capitalize();
last = document.getElementById(b).value.capitalize();
fullName = first + " " + last ;
console.log(fullName);
document.getElementById(c).value = fullName;
}
}
//Replace the ID's below with your form's field ID's
splitFullName("firstName","lastName","fullName");
Source: http://developers.marketo.com/blog/add-a-full-name-field-to-a-marketo-form/
来源:http: //developers.marketo.com/blog/add-a-full-name-field-to-a-marketo-form/
回答by Nick Schwab
Watch out for edge-cases like only a first name being provided or two or more spaces being entered. If you only want to parse out the first and last name, this will do the trick (full name should always contain at least 1 character to avoid first_name being set to an empty string):
注意边缘情况,例如只提供一个名字或输入两个或多个空格。如果您只想解析名字和姓氏,这可以解决问题(全名应始终包含至少 1 个字符,以避免将 first_name 设置为空字符串):
var full_name_split = "Paul Steve Panakkal".split(" ");
var first_name = full_name_split[0];
var last_name = full_name_split.length > 1 ? full_name_split[full_name_split.length - 1] : null;
回答by Marius
A comenter said What if want first name to be "Paul" and last name "Steve Panakkal"
一位评论员说,如果希望名字是“Paul”,姓氏是“Steve Panakkal”怎么办?
var name = "Paul Steve Panakkal" // try "Paul", "Paul Steve"
var first_name = name.split(' ')[0]
var last_name = name.substring(first_name.length).trim()
console.log(first_name)
console.log(last_name)