views:

68

answers:

1

I need parse a string inside a parenthesis, which looks like (A, B, C), where A, B, and C are string that can contain any legal JavaScript code. For example, B might be a very long string with nested structures similar to (A, B, C). What would be the best way to parse such a string?

An example of the string to parser is invoking a function:

func( parameter 1, parameter 2, parameter 3)

where all the three parameters could be other function definitions.

+1  A: 

One of the simplest ways to create such a parser is to write a recursive descent parser. This type of parser is relatively easy to create and is certainly easier to understand than more complex parser generators (such as "yacc" and the like).

Greg Hewgill
Is there any such a parser implemented in JavaScript?
Paul
@Paul: I found a few with a Google search for "javascript recursive descent". However, usually a recursive descent parser is something you just write for your particular grammar. The structure of the grammar closely mirrors the structure of the parser itself (as you can see from the examples on Wikipedia).
Greg Hewgill
@Paul: If you need to parse actual JavaScript source code, then building a parser that handles all cases can be quite a project in itself. If you can restrict your input to a subset of JavaScript, you may have a considerably easier time. Also, with regard to regular expressions: Regular expressions can parse [regular languages](http://en.wikipedia.org/wiki/Regular_language), which is a specific term in formal language theory. Any language (such as JavaScript) with arbitrarily deeply nested structures is *not* a regular language.
Greg Hewgill