Home > OS >  How to get first and last name when someone enters full name in Javascript?
How to get first and last name when someone enters full name in Javascript?

Time:05-28

How to get someone's first and last name when they enter their full name if someone's first and/or last name is more than 1 word each? Like for example "Juan García Reyes" where "García Reyes" is the last name, or "Anne Marie Smith" where Anne Marie is the first name.? I have this:

set fullName(value) {
  const parts = value.split(" ");
  this.firstName = parts[?];
  this.lastName = parts[?]
}

or this:

set fullName(value) {
    [this.firstName, this.lastName] = value.split(' ');
  }

but they only work when the first and last name are both only 1 word. I'm a beginner so please forgive me if this is a bit stupid!

CodePudding user response:

It's just not possible without additional information. How could you ever know if someone has 2 first names or 2 last names without manually reading each value to make a decision on where the split is. The only way to solve this is to have 2 separate input fields

CodePudding user response:

You cannot guess what kind of data your user will inform, they can provide either one, two or three words, being the firstname the first two or only the first one, for example. But you can make them inform the way you want. Try setting meaningful inputs, one for first name and another one for last name.

CodePudding user response:

make two seperate inputs and let the user write their first name in one and last name in the other. javascript has no ability to detect a first/last name and writing code for it seems crazy when you can just have two seperate inputs

CodePudding user response:

First read this

https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/

I do not recommend it, but you can do

const value = "John John James";
const parts = value.split(" ");
const lastName = parts.pop()
const firstName = parts.join(" ")

console.log(lastName)
console.log(firstName)

  • Related