How to move the first word to the end of a string in JavaScript

2 Answers

0 votes
function move_first_word_to_end_of_string(s) {
    const parts = s.trim().split(/\s+/);

    if (parts.length <= 1) {
        return s.trim();
    }

    const first = parts.shift();
    parts.push(first);

    return parts.join(" ");
}

const s = "Would you like to know more? (Explore and learn)";
const result = move_first_word_to_end_of_string(s);

console.log(result);



/*
run:

you like to know more? (Explore and learn) Would

*/

 



answered Feb 5 by avibootz
0 votes
function moveFirstWordToEndOfString(s) {
  const parts = s.trim().split(/\s+/);
  if (parts.length <= 1) return s;

  return [...parts.slice(1), parts[0]].join(" ");
}

const s = "Would you like to know more? (Explore and learn)";
const result = moveFirstWordToEndOfString(s);

console.log(result);



/*
run:

you like to know more? (Explore and learn) Would

*/

 



answered Feb 5 by avibootz
...