How to remove a random word from a string in TypeScript

1 Answer

0 votes
function removeRandomWord(str: string): string {
    let words: string[] = str.split(" ");
    if (words.length === 0) return str;

    let randomIndex: number = Math.floor(Math.random() * words.length);
    words.splice(randomIndex, 1); // Remove the randomly selected word

    return words.join(" ");
}

const str: string = "I'm not clumsy The floor just hates me";
const result: string = removeRandomWord(str);

console.log(result);



/*
run:

"I'm not clumsy The just hates me" 

*/

 



answered May 5, 2025 by avibootz
...