所以我正在用html5 / javascript编写一个在线疯狂的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;
我有更多,但没有必要展示,除非你们因为任何原因需要更新。
答案 0 :(得分:1)
要替换JavaScript字符串中的值,可以使用.replace()方法。它有两个参数 - 用于查找匹配项的正则表达式或字符串,以及用于替换匹配项的新字符串。更详细,您可以在http://www.w3schools.com/jsref/jsref_replace.asp阅读。但就我而言,这种方式与使用相同键子串(例如Noun1)的大文本一起使用要好得多。