繁体   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