Home > Net >  Split a string (list of author names) into named components I can manipulate
Split a string (list of author names) into named components I can manipulate

Time:11-08

I have a string containing a list of names (authors of a book)

"John Doe, Jim Smith, Jane Elizabeth Doe"

I want to output a string:

'"Doe, John", "Smith, Jim", "Doe, Jane Elizabeth"'

I managed to work it out for a single author.

let fullName = "John Doe";
let pieces = fullName.split(" ");
var lastName, firstName; 
  if (pieces.length >= 2) {
    firstName = pieces[0];
    lastName = pieces[pieces.length - 1];
  } else {
    firstName = pieces[0];
    lastName = "";
  }
let lastFirst = '"'   lastName   ", "   firstName   '"';

I think I need to do something like this...

let fullName = "John Doe, Jim Smith, Jane Elizabeth Doe";
  if (fullName.includes(",")) {
    let author = fullName.split(", ");
    var arrayLength = author.length;
    for (var i = 0; i < arrayLength; i  ) {
        let pieces = author[i].split(" ");
    }
  }

but now I'm stuck, any assistance is greatly appreciated.

CodePudding user response:

You can try the below approach with some comments

const input = "John Doe, Jim Smith, Jane Elizabeth Doe"

const names = input.split(",")

const result = []

for (const name of names) {
  const nameParts = name.trim().split(" ") //remove reluctant space and break the string down into array items (names)
  const lastName = nameParts.pop() //take the last item
  nameParts.unshift(lastName   ",") //add the last item to the first position
  result.push(`"${nameParts.join(" ")}"`) //add "" to a name
}

const output = result.join(",") //make the entire array to become a string with a separator `,`


console.log(output)

CodePudding user response:

You were on the right track and almost got it. After getting the pieces array you just need to form a new string by changing the order of words in pieces.

let fullName = "John Doe, Jim Smith, Jane Elizabeth Doe";
  if (fullName.includes(",")) {
    let author = fullName.split(", ");
    var arrayLength = author.length;
    var res = [];
    for (var i = 0; i < arrayLength; i  ) {
        let pieces = author[i].split(" ");
        let newName = "\""   pieces[1]   ", "   pieces[0]   "\"";
        res.push(newName);
    }
  }

This is assuming all names consist of only 2 words. If there are more words within a name (for example, if you have a middle name as well), you can loop over the pieces array in reverse and append the individual words into newName assuming that you would still want to display the names in reverse order.

  • Related