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

1 Answer

0 votes
function moveWordToEnd(s, word) {
  // Split on whitespace
  const parts = s.trim().split(/\s+/);

  // Find and remove the first occurrence
  const index = parts.indexOf(word);
  if (index !== -1) {
    parts.splice(index, 1); // remove it
    parts.push(word);       // append at end
  }

  // Rebuild the string
  return parts.join(" ");
}

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

const result = moveWordToEnd(s, word);
console.log(result);



/*
run:

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

*/

 



answered Feb 5 by avibootz
...