Parsing Text with Javascript

I am trying to use Javascript to parse text that has been entered into a text field that would combine many user variables to create random actions. This may make more sense by looking at an example. As an example, you can specify:

  Activity
 @Home
 @Out

 @Home
 Read @book for @time
 Clean up @room for @time

 @Out
 Eat at atrestaurant

 @book
 Enders game
 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 will be used to separate the different categories.

Then the result will be determined randomly from this input, for example:

"Eat at Starbucks." or "Read the Lord of the Rings for 60 minutes." or "Clean the garage for 30 minutes."

Is this doable? It sounds like it should be pretty simple, but I don't know where to start. Any suggestions?

Thanks,

Albert

+6
javascript parsing
source share
2 answers

No problem. Divide the text field value into an array based on line break characters. Then go through the array one element at a time, sorting the values ​​in the variables for each section. Finally, use the JavaScript random number generator to randomly determine which of each group to choose. Output to the user by assigning a value to the HTML element.

+5
source share

What 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 eg 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 is not too difficult, but it does the job. Not tested though, but something like this should work. And where's the fun if it just worked, D

+10
source share

All Articles