简体   繁体   中英

loop through a string and replace specific values? Javascript

So I'm writing an online mad lib application in html5/javascript, and as of now I personally removed the words I want the user to replace, and injected their value. I want to get the program to loop through a string(the story) and replace the words I have chosen in every case in an array,with the words they have input. As an example if i want Noun1 to be the word "hill" and the word they input for Noun1 was "ferret" then every time the story would say "hill" it will be replaced with the word "ferret". Would using a string and an array be the best course of action or is there a better way? and would you mind showing me how to loop through a string in java-script and how to replace values?

This is what I currently have.

 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;

I have bit more, but it is unnecessary to show, unless you guys need it for whatever reason ill update.

To replace values in the JavaScript string, you can use .replace() method. It gets two arguments - the regular expression or string to find matches, and new string to replace the matches. More detailed, you can read at http://www.w3schools.com/jsref/jsref_replace.asp . But as for me, this way is much better to be used with big texts where same key substring (Noun1 , for example), happens a lot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM