Parsing text with Javascript
I'm trying to use Javascript to parse text that has been entered in a text box - which would combine a variety of user-generated variables to create random activities. This might make more sense looking at the example. Some example input might be:
Activity @Home @Out @Home Read @book for @time Clean up @room for @time @Out Eat at at @restaurant @book Enders G开发者_如何学Pythoname Lord of the Rings @room bedroom garage basement @restaurant Red Robin McDonalds Starbucks @time 15 minutes 30 minutes 45 minutes 60 minutes
Pound/and signs would be used to separate different categories.
The output would then be determined randomly from the given input, for example:
"Eat at Starbucks." or "Read Lord of the Rings for 60 minutes." or "Clean garage for 30 minutes."
Is this doable? It seems like it should be fairly straightforward, but I do not know where to start. Any suggestions?
Thanks,
Albert
How about:
var myText = ...; // Input text
var lines = myText.split("\n");
var numLines = lines.length;
var i;
var currentSection;
var sections = Array();
var phrases = Array();
// parse phrases
for (i = 0; i < numLines; i++) {
var line = lines[i];
if (line.indexOf('@') == 1) {
// start of e.g. time section, handled in nex loop
break;
} else {
// phrase
phrase.push(line);
}
}
// parse sections
for ( ; i < numLines; i++) {
var line = lines[i];
if (line.indexOf('@') == 1) {
// start of next section, handled in nex loop
currentSection = line;
sections[currentSection] = new Array();
} else {
// add section entry
sections[currentSection].push(line);
}
}
It's not too sophisticated, but does the job. Didn't test it though, but something like this should work. And where is the fun if this'd just work ;D
No issue at all. Split the textbox value into an array based on line break characters. Then, go through the array one element at a time, sorting the values into variables for each section. Finally, use JavaScript's random number generator to randomly determine which of each group to select. Output to the user by assigning the value to an HTML element.
精彩评论