0

だから私はhtml5/javascriptでオンラインのmadlibアプリケーションを書いています、そして今のところ私はユーザーに置き換えて欲しい単語を個人的に削除し、それらの価値を注入しました。プログラムに文字列(ストーリー)をループさせて、配列内のすべての場合に選択した単語を、入力した単語に置き換えたいと思います。例として、Noun1を「hill」という単語にし、Noun1に入力した単語を「ferret」とすると、ストーリーに「hill」と表示されるたびに、「ferret」という単語に置き換えられます。文字列と配列を使用することが最善の行動でしょうか、それともより良い方法がありますか?java-scriptで文字列をループする方法と、値を置き換える方法を教えていただけませんか。

これは私が現在持っているものです。

 function makeML(){
   //get variables from form
   var firstNoun = window.document.myForm.txtfirstNoun.value;
   var secondNoun = document.myForm.txtsecondNoun.value;
   var firstVerb = document.myForm.txtfirstVerb.value;
   var thirdNoun = document.myForm.txtthirdNoun.value;
   var fourthNoun = document.myForm.txtfourthNoun.value;
   var secondVerb = document.myForm.txtsecondVerb.value;
   var firstBody = document.myForm.txtfirstBody.value;
   var story = "";
   story = "Hansel and Gretel sat by the " ;
   story += firstNoun;
   story += ". and when noon came, each ate a little piece of ";
   story += secondNoun;
   story += ", and as they heard the  ";
   story += firstVerb;
   story += " of the wood-axe, they believed that their father was near. It was not the  axe; however, but a ";
   story += thirdNoun;
   story += " which he had fastened to a ";
   story += fourthNoun;
   story += " which the wind was blowing backwards and forwards. And as they had been ";
   story +=  secondVerb; 
   story += " such a long time, their ";
   story +=  firstBody; 
   story += " closed with fatigue, and they fell fast asleep." 

   story += "!\"  \nThe End.... or is it."

   document.myForm.txtStory.value = story;

もう少しありますが、何らかの理由で更新が必要な場合を除いて、表示する必要はありません。

4

1 に答える 1

1

JavaScript 文字列の値を置き換えるには、.replace() メソッドを使用できます。2 つの引数を取得します。一致を見つけるための正規表現または文字列と、一致を置き換える新しい文字列です。詳細については、http://www.w3schools.com/jsref/jsref_replace.aspを参照してください。しかし、私にとっては、この方法は、同じキー部分文字列 (たとえば、 Noun1 ) が頻繁に発生する大きなテキストで使用する方がはるかに優れています。

于 2013-03-11T14:35:02.427 に答える