簡體   English   中英

遍歷字符串並替換特定值? Java腳本

[英]loop through a string and replace specific values? Javascript

因此,我正在用html5 / javascript編寫一個在線mad lib應用程序,到目前為止,我個人刪除了我希望用戶替換的單詞,並注入了它們的價值。 我想讓程序遍歷字符串(故事),並用輸入的單詞替換在每種情況下我在數組中選擇的單詞。 例如,如果我希望Noun1成為單詞“ hill”,而他們為Noun1輸入的單詞是“ ferret”,那么每次故事說“ hill”時,它將被單詞“ ferret”代替。 使用字符串和數組是最好的方法,還是有更好的方法? 您介意向我展示如何在Java腳本中循環訪問字符串以及如何替換值嗎?

這就是我目前所擁有的。

 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;

我還有更多,但沒有必要顯示,除非你們出於任何原因需要更新。

要替換JavaScript字符串中的值,可以使用.replace()方法。 它有兩個參數-用於查找匹配項的正則表達式或字符串,以及用於替換匹配項的新字符串。 更詳細的信息,您可以在http://www.w3schools.com/jsref/jsref_replace.asp上閱讀。 但是對我來說,這種方法最好用於大文本,而大文本經常出現相同的鍵子字符串(例如Noun1)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM