テキストからランダムな単語を選択し、それを別の単語に置き換えるコードをJavaScriptで書きたいと思います。
これが私のコードです:
var text = "dog cat apple stone";
var keyword = text[Math.floor(Math.random()*text.length)]; // select random word
var new_phrase = text.replace( keyword, "house"); // replace for other word
document.write("<p>" + text + "</p>" );
document.write("<p>" + new_phrase + "</p>");
ただし、これは単語ではなくテキスト内の文字を置き換えます。このように:「犬のチョゼット リンゴの石」
文字ではなくランダムな単語を選択するにはどうすればよいですか?