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

1 Answer

0 votes
function moveNthWordToEndOfString(input: string, n: number): string {
    if (input.trim() === "") {
        return input;
    }

    const parts: string[] = 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);
    parts.push(word);

    return parts.join(" ");
}

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

const result: string = moveNthWordToEndOfString(s, n);

console.log(result);
 
 
  
  
/*
run:
  
"Would you to know more? (Explore and learn) like" 
  
*/

 



answered Feb 6 by avibootz
...