6 回答
TA贡献1836条经验 获得超5个赞
你可以这样做: -
[fName, mName, lName] = nameString.split(" ");
if(!lName) lName = mName
else fName = fName+mName
因此,如果姓氏为 null 或未定义,那么我们将中间名值分配给姓氏。否则名字将等于名字 + 中间名。
TA贡献1829条经验 获得超6个赞
这个怎么样?
const name = "Sachin Ramesh Tendulkar"
const lstSpc = name.lastIndexOf(" ")
const nameParts = [name.substring(0, lstSpc), name.substring(lstSpc)]
console.log(nameParts)
TA贡献1783条经验 获得超4个赞
尝试这个。
name = 'ABC XYZ GHI';
array = name.split(' ');
lastName = array.pop()
firstName = array.join(' ')
TA贡献1807条经验 获得超9个赞
久经考验
const name = "Sachin Ramesh Tendulkar"
const array = name.split(' ')
let firstname = ''
let lastname = ''
if (array.length && array.length > 1) {
array.forEach((item, i) => {
if ((array.length - 1) !== i) {
if (firstname) {
firstname = firstname + " " + item
} else {
firstname = item
}
}
})
lastname = array[array.length - 1]
}
if (array.length === 1) {
firsname = array[0]
}
TA贡献1784条经验 获得超2个赞
var fullName = "Sachin Ramesh Tendulkar Second";
var firstName = fullName.substring(0, fullName .lastIndexOf(" ") + 1);
var lastName = fullName.substring(fullName .lastIndexOf(" ") + 1);
console.log(`firstName: `, firstName);
console.log(`lastName: `, lastName);
TA贡献1872条经验 获得超3个赞
shift将删除第一个元素。我认为您想要的是pop获取最后一个元素以隔离姓氏。请注意,这些是直接突变
var fullName = "Sachin Ramesh Tendulkar Second".split(' ');
var lastName = fullName.pop();
var firstName = fullName.join(' ');
console.log(`firstName: `, firstName);
console.log(`lastName: `, lastName);
添加回答
举报