0

所以我正在用 html5/javascript 编写一个在线 mad lib 应用程序,截至目前我个人删除了我希望用户替换的单词,并注入了它们的值。我想让程序循环遍历一个字符串(故事),并用他们输入的单词替换我在数组中每种情况下选择的单词。例如,如果我希望 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() 方法。它有两个参数——查找匹配的正则表达式或字符串,以及替换匹配的新字符串。更详细的,您可以在http://www.w3schools.com/jsref/jsref_replace.asp阅读。但就我而言,这种方式更适合用于相同键子字符串(例如 Noun1 )发生很多的大文本。

于 2013-03-11T14:35:02.427 回答