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 fro
You needn't use any split method and create unnecessary arrays for that operation. Just use lastIndexOf and substring methods of javascript.
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
Use the following code, it works for me
let name = "Paul Steve Panakkal"
let parts = name.split(' ')
let firstName = parts.shift(); // Paul
let lastName = parts.join(' '); // Steve Panakkal
console.log({
firstName,
lastName
})
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];
}
var firstName = fullName.split(" ")[0];
Yes:
var fullName = "Paul Steve Panakkal".split(' '),
firstName = fullName[0],
lastName = fullName[fullName.length - 1];
References:
This way, both firstName and lastName are always correct
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(' ');
}