Search code examples
javascriptconcatenation

How can I concatenate the last name and remove the middle name?


I am trying to concatenate the last name and remove the middle name

fullName = "De Risio, Paul William";

fullName.split(','); // complete last name to array

lastName = fullName[0]; // get complete last name

tmp = lastName.split(" ").join(""); // remove space in lastName

firstAndMid = fullName[1]; // get string after "," delimiter

firstAndMid.split(" "); // first and middle name delimited with " " to array

firstName = firstAndMid[0]; // get only first name

alert(tmp + ", " +firstName);   // ==> D, e

The problem is I want "DeRisio, Paul" and instead I am getting "D, e". I am pretty far off the mark. What gives?


Solution

  • You're not assigning the result of split to anything, so you are still working on the strings instead of an array when you do e.g. lastName = fullName[0];.

    fullName = "De Risio, Paul William";
    
    names = fullName.split(/,\s*/); // complete last name to array
    
    lastName = names[0]; // get complete last name
    
    tmp = lastName.split(" ").join(""); // remove space in lastName
    
    firstAndMid = names[1]; // get string after "," delimiter
    
    first = firstAndMid.split(" "); // first and middle name delimited with " " to array
    
    firstName = first[0]; // get only first name
    
    console.log(tmp + ", " +firstName);   // ==> D, e

    Note you need to split on , followed by spaces (/,\s*/), otherwise first[0] will be an empty string due to the space at the start of firstAndMid.