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

1 Answer

0 votes
function moveNthWordToEndOfString(input, n) {
    if (typeof input !== "string" || input.trim() === "") {
        return input;
    }

    const parts = input.trim().split(/\s+/);

    if (n < 0 || n >= parts.length) {
        throw new RangeError(`Index ${n} is out of range.`);
    }

    const word = parts.splice(n, 1)[0];
    parts.push(word);

    return parts.join(" ");
}

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

const result = moveNthWordToEndOfString(s, n);

console.log(result);




/*
run:

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

*/

 



answered Feb 6 by avibootz
...