0

テキストからランダムな単語を選択し、それを別の単語に置き換えるコードを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>");

ただし、これは単語ではなくテキスト内の文字を置き換えます。このように:「犬のチョゼット リンゴの石」

文字ではなくランダムな単語を選択するにはどうすればよいですか?

4

3 に答える 3

2

を使用しtext[someIndex]て、から1つの文字を選択していますtext。文字列を分割して、結果の配列を使用してみてください。

var text = "dog cat apple stone"
   ,txttmp = text.split(/\s+/)
   ,keyword = txttmp[Math.floor(Math.random()*txttmp.length)];
于 2013-01-14T08:59:14.603 に答える
1

Kepp itによると、単純な原則だと思います

var text = "dog cat apple stone";
arrText = text.split(" ");

それはあなたと単語の配列を返します。配列内の単語を置き換えた後、再び使用できます

arrText.join(" ");
于 2013-01-14T08:59:14.767 に答える
0

配列の使用

http://www.w3schools.com/jsref/jsref_obj_array.asp

値を保存してから、インデックスを使用してそれらを参照し、値を取り戻すことができます。

var text=["dog","cat","apple", "stone"];

var keyword = Math.floor((Math.random()*text.length)); 
text[keyword] = "house"; // replace for other word

document.write("<p>" + text + "</p>" );
于 2013-01-14T09:09:07.663 に答える