我有一个名为Paul Steve Panakkal的用户。这是一个长名称,它不适合 div 容器。那么无论如何使用 JavaScript 或 jQuery 将名字和姓氏从中分离出来吗?
该名称是从 PHP 获取到 JavaScript 中的变量中的。然后使用 JS 对其进行拆分。
我有一个名为Paul Steve Panakkal的用户。这是一个长名称,它不适合 div 容器。那么无论如何使用 JavaScript 或 jQuery 将名字和姓氏从中分离出来吗?
该名称是从 PHP 获取到 JavaScript 中的变量中的。然后使用 JS 对其进行拆分。
您应该使用以下String.prototype.split()
方法:
'Paul Steve Panakkal'.split(' '); // returns ["Paul", "Steve", "Panakkal"]
你可以这样使用它:
'Paul Steve Panakkal'.split(' ').slice(0, -1).join(' '); // returns "Paul Steve"
'Paul Steve Panakkal'.split(' ').slice(-1).join(' '); // returns "Panakkal"
所以共同点:
var firstName = fullName.split(' ').slice(0, -1).join(' ');
var lastName = fullName.split(' ').slice(-1).join(' ');
是的:
var fullName = "Paul Steve Panakkal".split(' '),
firstName = fullName[0],
lastName = fullName[fullName.length - 1];
参考:
在西班牙语中,这可能很棘手,因为您可能有第二个可选名称,甚至是复杂的姓氏,如“del Bosque”或“de la Hoya”、带有重音符号的元音和ñ。以下 javascript 能够解析完整的西班牙名称,因为您在编写它时会考虑大写和小写。它会返回一个json给你
代码是:
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;
}
如果您要指定第二个名字,则姓氏是必需的。试试看:
甚至尝试一个复杂的,比如
评论你的经历。
我认为,是时候开始使用正则表达式了 :)
"Paul Steve Panakkal".split(/(\s).+\s/).join("") // "Paul Panakkal"
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(' ');
}
我尝试了下面的代码,它对我来说很酷
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());
在上面的例子中:
(1)
If full_name = 'xyz abc pqr';
first_name = "xyz";
last_name = "abc pqr";
(2)
If `full_name = "abc"`:
Then first_name = "abc";
and last_name = "";
一位评论者说如果想要名字是“保罗”而姓氏是“史蒂夫·帕纳卡尔”怎么办?
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)
最常见的解决方案,我们总是将第一个单词作为名字,其余的作为姓氏:
const splitName = (name = '') => {
const [firstName, ...lastName] = name.split(' ').filter(Boolean);
return {
firstName: firstName,
lastName: lastName.join(' ')
}
}
console.log(splitName('Jon Snow'));
console.log(splitName(' Jon '));
console.log(splitName(' Jon The White Wolf '));
如果您假设最后一个单词是姓氏并且单个单词名称也是姓氏,那么...
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];
}
注意边缘情况,例如仅提供名字或输入两个或多个空格。如果您只想解析名字和姓氏,这将解决问题(全名应始终包含至少 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;
使用此代码:
您需要更改该行: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");
来源:http: //developers.marketo.com/blog/add-a-full-name-field-to-a-marketo-form/
您无需使用任何拆分方法并为该操作创建不必要的数组。只需使用javascript 的lastIndexOf和substring方法。
var s = "Paul Steve Panakkal";
var a = s.lastIndexOf(' '); // last occurence of space
var b = s.substring(0, a); // Paul Steve
var c = s.substring(a+1); // Panakkal
const fullName = 'Paul Steve Panakkal'.split(' ');
const lastName = fullName.pop(); // 'Panakkal'
const firstName = fullName.join(' '); // 'Paul Steve'
console.log(firstName);
console.log(lastName);
使用以下代码,它适用于我
let name = "Paul Steve Panakkal"
let parts = name.split(' ')
let firstName = parts.shift(); // Paul
let lastName = parts.join(' '); // Steve Panakkal
console.log({
firstName,
lastName
})
var firstName = fullName.split(" ")[0];
另一种选择可能是使用正则表达式。
\w+\s\w+(?=\s)|\w+
上面的正则表达式将找到匹配两个或三个命名类型组合的字符串模式firstName
。lastName
const regex = /\w+\s\w+(?=\s)|\w+/g;
const name1 = 'Paul Steve Panakkal';
const [firstName1, lastName1] = name1.trim().match(regex);
console.log(`${firstName1} | ${lastName1}`);
const name2 = 'John Doe';
const [firstName2, lastName2] = name2.trim().match(regex);
console.log(`${firstName2} | ${lastName2}`);
细节
\w+
匹配任何单词字符。?=\s
匹配任何空白字符但不捕捉它。有很多方法可以存档这个。
我认为最简单的方法是拆分并弹出姓氏。
let fullname = 'Paul Steve Panakkal'; // from php
let tmpArray = fullname.split(' '); //split the name to an array
const lastname = tmpArray.pop(); // pop the last element of the aray and store it in "lastname" variable
const firstname = tmpArray.join(' '); // join the array to make first and middlename and store it in "firstname" variale
console.log("firstname:", firstname)
console.log("lastname:", lastname)
split
使用带有空格的JS作为分隔符。
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/split
如果您的意思是姓氏是名字之后的所有名字,只需使用:
var name = "Paul Steve Panakkal";
var arrName = name.split(" ");
var firstName = arrName.slice(0, 1).join(' ');
var lastName = arrName.slice(1, arrName.length).join(' ');
这样,firstName 和 lastName 总是正确的
var names = fullName.split(' ');
if (!names || names.length <= 1) {
firstName = this.name;
lastName = '';
} else {
firstName = names.slice(0, -1).join(' ');
lastName = names.slice(-1).join(' ');
}
var fullName = "Paul Steve Panakkal";
您可以使用 split 函数拆分全名,然后拆分结果,例如在数组或列表中显示元素。
这就是您使用 split 功能时发生的情况。
fullName.split(" ")
["Paul", "Steve", "Panakkal"]
这不会保存到任何变量中。您可以执行拆分功能并将元素分配给这样定义明确的变量。
var firstName = fullName.split(" ")[0];
var lastName = fullName.split(" ")[1];
var otherName = fullName.split(" ")[2];
我想出了这个逻辑:
const fullName = "Paul Steve Panakkal";
const idx = fullName.lastIndexOf(' ');
const firstName = idx !== -1 ? fullName.substring(0, idx) : fullName;
const lastName = idx !== -1 ? fullName.substring(idx + 1) : '';
console.log('firstName:', firstName, 'lastName:', lastName);
输出:
firstName: Paul Steve lastName: Panakkal
" Paul Steve ".trim().split(/(\s).+\s/).join("") // 'Paul Steve'
您应该添加trim()以防用户不小心输入了额外的空格!
如果您希望姓氏是名字之后的所有名字:
function splitFirstLast(name) {
return {
firstName: name.indexOf(' ') !== -1 && name.substring(0, name.indexOf(' ')) || name,
lastName: name.indexOf(' ') !== -1 && name.substring(name.indexOf(' ') + 1) || ''
}
}
对象可以通过一个简单的函数来解决问题:
const fullName = "Edgar Allan Poe"
const formatter = (name) => {
const splitedName = name.trim().split(' ')
if(splitedName.length === 0) return ""
//here happens the hack!, it prevents duplicate names
//JS objects overrides duplicate keys, very useful here
const output = {
[splitedName[0]]: splitedName[0],
//storing first key
[splitedName[splitedName.length - 1]]: splitedName[splitedName.length - 1]
//storing last key (whose may be first key)
}
return Object.keys(output).join(' ').trim()
//now convert object keys into a string. "E pronto rs"
}
console.log(formatter(fullName)) // "Edgar Poe"
console.log(formatter("Elias")) // "Elias"
console.log(formatter("")) // ""