Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to String Split in javascript

I have a string

fullName = ‘Ross beddy washington andres’

I need to split this in to firstName, middleName and lastName.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

You can use array manipulation methods to achieve this.

const fullName = 'Ross beddy washington andres';
const nameSplit = fullName.split(' ');

const names = {};

if (nameSplit.length >= 2) {
    if (nameSplit.length === 2) {
        names.lastName = nameSplit[0];
        names.firstName = nameSplit[1];
        names.middleName = '';
    } else if (nameSplit.length === 3) {
        names.lastName = nameSplit[0] + ' ' + nameSplit[1];
        names.firstName = nameSplit[2];
        names.middleName = '';
    } else if (nameSplit.length === 4) {
        names.lastName = nameSplit[0] + ' ' + nameSplit[1];
        names.firstName = nameSplit[2];
        names.middleName = nameSplit[3];
    } else {
        names.lastName = nameSplit.slice(0, -2).join(' ');
        names.firstName = nameSplit[nameSplit.length - 2];
        names.middleName = nameSplit[nameSplit.length - 1];
    }
} else {
    console.log('Invalid name format');
}

console.log(names);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading