How to replace a random word in a string with a random word from an array of words using JavaScript

1 Answer

0 votes
function replaceRandomWord(text, replacementWords) {
  const words = text.split(" ");

  if (words.length === 0 || replacementWords.length === 0) {
    return text; // nothing to do
  }

  // Pick random index in the sentence
  const idx = Math.floor(Math.random() * words.length);

  // Pick random replacement word
  const newWord = replacementWords[Math.floor(Math.random() * replacementWords.length)];

  // Replace it
  words[idx] = newWord;

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

const text = "The quick brown fox jumps over the lazy dog";
const replacementWords = ["c#", "c++", "java", "rust", "python"];

const result = replaceRandomWord(text, replacementWords);
console.log(result);



/*
run:

The quick brown fox c++ over the lazy dog

*/

 



answered Feb 13 by avibootz

Related questions

...