skip to Main Content

I have names from a database in this format:

lastname mi firstname

And I’d like to change it to

firstname mi lastname

However, I keep getting a numeric value using the stuff Google has told me to do so far:

let s = 'lastname mi firstname'
let sa = s.split(' ')
let correctOrder = sa.unshift(sa.pop())  // 3
let correctOrder = sa.push(sa.shift());  // 3

What is the correct way to move firstname from the last position into the first?

3

Answers


  1. A universal solution regardless of number of words between:

    const str = 'lastname mi mi2 firstname';
    
    const arr = str.split(' ');
    const [first, last] = [arr.pop(), arr.shift()];
    
    console.log([first, ...arr, last].join(' '));

    A regex universal solution:

    const str = 'lastname mi mi2 firstname';
    
    console.log(str.replace(/^(w+)(.+?)(w+)$/, '$3$2$1'));
    Login or Signup to reply.
  2. if there’re only 3 words you could use destructuring and .join():

    let s = 'lastname mi firstname'
    let [s1,s2,s3] = s.split(' ');
    let res = [s3,s2,s1].join(' ');
    console.log(res)

    regex approach:

    let s = 'lastname mi firstname';
    let res = s.replace(/^(w+)s(w+)s(w+)$/, '$3 $2 $1');
    console.log(res);

    Another approach using Array#reverse

    let s = 'lastname mi firstname';
    let res = s.match(/(w+)/g).reverse().join(' ');
    console.log(res);

    with Array#pop and Array#shift methods:

    let s = 'lastname mi firstname';
    let names = s.split(' ');
    let res = [names.pop(), names.pop(), names.shift()].join(' ');
    console.log(res);
    Login or Signup to reply.
    1. .split(" ") the string at every space: " " into an array of strings

       "last mi first".split(" ");
       // returns an array of strings: ["last", "mi", "first"]
      
    2. Next .reverse() the array of strings

       ["last", "mi", "first"].reverse();
       // returns an array in reversed order: ["first", "mi", "last"]
      
    3. Finally, .join(" ") the array of strings into a string with a space between the words

       ["first", "mi", "last"].join(" ");
       // returns a string with a space between words: "first mi last"
      

    In the example below is a one-line function — each Array method is chained.

    const fullName = "Christ H Jesus";
    
    const fml = name => name.split(' ').reverse().join(' ');
    
    console.log(fml(fullName));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search