Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 626
Albert Avatar asked Jan 08 '10 00:01

Albert


People also ask

How do you parse a string in JavaScript?

Use the JavaScript function JSON. parse() to convert text into a JavaScript object: const obj = JSON. parse('{"name":"John", "age":30, "city":"New York"}');

What is parsing in JavaScript?

Parsing means analyzing and converting a program into an internal format that a runtime environment can actually run, for example the JavaScript engine inside browsers. The browser parses HTML into a DOM tree.

How do you parse a variable in JavaScript?

var num = 12; var greeting = "Hello"; SayGreeting(greeting, num); If your number is actually a string and you want to change it into a number, you can do that like this: var num = "12"; var greeting = "Hello"; SayGreeting(greeting, +num); The + in front of the string, will attempt to parse the string into a number.


1 Answers

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

like image 157
Mene Avatar answered Oct 26 '22 20:10

Mene