I have a string
fullName = ‘Ross beddy washington andres’
I need to split this in to firstName, middleName and lastName.
Rule to split the names:
when receiving 2 words: 1st LastName / firstName
when receiving 3 words: 1st LastName / 2nd LastName / firstName
when receiving 4 words: 1st LastName / 2nd LastName / firstName/ MiddleName
when receiving 5 or more than 5 words follow the rule for 4 words
For above example below will be the output:
firstName = washington
middleName = andres
lastName = Ross beddy
my code:
const fullName = 'Ross beddy washington andres';
const names = {};
const nameSplit = fullName.split(' ');
if (nameSplit.length == 4) {
names.firstName = nameSplit[2];
names.lastName = nameSplit[0] + ' ' + nameSplit[1];
names.middleName = nameSplit[3];
} else if (nameSplit.length == 3) {
names.firstName = nameSplit[2];
names.lastName = nameSplit[0] + ' ' + nameSplit[1];
names.middleName = '';
} else if (nameSplit.length == 2){
names.firstName = nameSplit[1];
names.lastName = nameSplit[0] ;
names.middleName = ''
}
console.log(names);
How to include the logic if there are more than 4 words ? is there any elegant way to do this!
3
Answers
You can use array manipulation methods to achieve this.
Your code looks almost correct, but you need to handle the case when there are 5 or more words in the name. According to your rules, you should treat it as if there are 4 words. Here’s an updated version of your code:
This code checks if the length of nameSplit is greater than or equal to 4 and treats it as 4 words according to your rules. Otherwise, it follows your original logic for 3 words and 2 words. Additionally, it handles the case when the input doesn’t match any of these scenarios by printing "Invalid input."
Do you mean something like:
If the names array has more than 4 elements, the middleName variable is assigned the value of all the remaining elements in the names array, joined together into a string using the join method.