How to remove a random word from a string in JavaScript

1 Answer

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

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

    return words.join(" ");
}

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

console.log(result);



/*
run:

I'm not clumsy The floor hates me

*/

 



answered May 5, 2025 by avibootz
edited May 5, 2025 by avibootz
...