Search code examples
javascriptstringsplitreverseswap

Flip first name and last name to last name first name


I'm trying to swap the first names and last names of from textarea

Input: John Doe

Jane Doe

Joe Doe

Joan Doe

Jenny van Doe

Desired output: Doe, John

Doe, Jane

Doe, Joe

Doe, Joan

van Doe, Jenny

But getting: Doe Jane Doe Joe Doe Joan Doe Jenny van Doe, John

The logic is pretty simple, take the first string as first name and the rest as last name, if there are middename it will also be taken in as last name separated by a comma.

It is working with this code but only for a one liner. Hence if it's a list names from a textarea it will take first string as first name and assign the rest of the names to last name.

var splitName = document.getElementById("splitName");
splitName.onclick = function() {

  var fullname = document.getElementById("fullName").value;
  console.log(fullname);

  var spaceIndex = fullname.indexOf(" ");
  var firstname;
  var lastname;

  if (spaceIndex == -1) {
    lastname = fullname;
    lastname = "";
  } else {

    var firstname = fullname.substring(0, spaceIndex);
    var lastname = fullname.substr(spaceIndex + 1);
  }

  document.getElementById("result").innerHTML = lastname + ", " + firstname;


};
<div>
  <textarea cols="20" rows="5" id="fullName"></textarea>
</div>

<div id="splitName" class="hwbutton">Reverse</div>

<div id="result"></div>


Solution

  • You can use split() to separate the lines and then use a loop.

    var splitName = document.getElementById("splitName");
    splitName.onclick = function() {
      document.getElementById("result").innerHTML = '';
      const value = document.getElementById("fullName").value;
      value.split('\n').forEach(fullname => {
    
        var spaceIndex = fullname.indexOf(" ");
        var firstname;
        var lastname;
    
        if (spaceIndex == -1) {
          lastname = fullname;
          lastname = "";
        } else {
          firstname = fullname.substring(0, spaceIndex);
          lastname = fullname.substr(spaceIndex + 1);
        }
    
        document.getElementById("result").innerHTML += lastname + ", " + firstname + "<br>";
      });
    };
    <div>
      <textarea cols="20" rows="5" id="fullName">Jane Doe
    Joe Doe
    Joan Doe
    Jenny van Doe</textarea>
    </div>
    
    <div id="splitName" class="hwbutton">Reverse</div>
    
    <div id="result"></div>