{"id":17974,"date":"2017-07-24T12:15:45","date_gmt":"2017-07-24T09:15:45","guid":{"rendered":"https:\/\/www.webcodegeeks.com\/?p=17974"},"modified":"2017-07-20T12:05:32","modified_gmt":"2017-07-20T09:05:32","slug":"parsing-javascript-tools-libraries","status":"publish","type":"post","link":"https:\/\/www.webcodegeeks.com\/javascript\/parsing-javascript-tools-libraries\/","title":{"rendered":"Parsing in JavaScript: Tools and Libraries"},"content":{"rendered":"<p><em>This is an article similar to a previous one we wrote: <a href=\"https:\/\/tomassetti.me\/parsing-in-java\/\">Parsing in Java<\/a>, so the introduction is the same. Skip to chapter 3 if you have already read it.<\/em><\/p>\n<p>If you need to parse a language, or document, from JavaScript there are fundamentally three ways to solve the problem:<\/p>\n<ul>\n<li>use an existing library supporting that specific language: for example a library to parse XML<\/li>\n<li>building your own custom parser by hand<\/li>\n<li>a tool or library to generate a parser: for example ANTLR, that you can use to build parsers for any language<\/li>\n<\/ul>\n<h2>Use An Existing Library<\/h2>\n<p>The first option is the best for well known and supported languages, like XML or HTML. A good library usually include also API to programmatically build and modify documents in that language. This is typically more of what you get from a basic parser. The problem is that such libraries are not so common and they support only the most common languages. In other cases you are out of luck.<\/p>\n<h2>Building Your Own Custom Parser By Hand<\/h2>\n<p>You could need to go for the second option if you have particular needs. Both in the sense that the language you need to parse cannot be parsed with traditional parser generators, or you have specific requirements that you cannot satisfy using a typical parser generator. For instance, because you need the best possible performance or a deep integration between different components.<\/p>\n<h2>A Tool Or Library To Generate A Parser<\/h2>\n<p>In all other cases the third option should be the default one, because is the one that is most flexible and has the shorter development time. That is why on this article we concentrate on the tools and libraries that correspond to this option.<\/p>\n<p><em>Note: text in blockquote describing a program comes from the respective documentation<\/em><\/p>\n<h2>Tools To Create Parsers<\/h2>\n<p>We are going to see:<\/p>\n<ul>\n<li>tools that can generate parsers usable from JavaScript (and possibly from other languages)<\/li>\n<li>JavaScript libraries to build parsers<\/li>\n<\/ul>\n<p>Tools that can be used to generate the code for a parser are called <strong>parser generators<\/strong> or <strong>compiler compiler<\/strong>. Libraries that create parsers are known as <strong>parser combinators<\/strong>.<\/p>\n<p>Parser generators (or parser combinators) are not trivial: you need some time to learn how to use them and not all types of parser generators are suitable for all kinds of languages. That is why we have prepared a list of the best known of them, with a short introduction for each of them. We are also concentrating on one target language: JavaScript. This also means that (usually) the parser itself will be written in JavaScript.<\/p>\n<p>To list all possible tools and libraries parser for all languages would be kind of interesting, but not that useful. That is because there will be simple too many options and we would all get lost in them. By concentrating on one programming language we can provide an apples-to-apples comparison and help you choose one option for your project.<\/p>\n<h2>Useful Things To Know About Parsers<\/h2>\n<p>To make sure that these list is accessible to all programmers we have prepared a short explanation for terms and concepts that you may encounter searching for a parser. We are not trying to give you formal explanations, but practical ones.<\/p>\n<h3>Structure Of A Parser<\/h3>\n<p>A parser is usually composed of two parts: a <em>lexer<\/em>, also known as <em>scanner<\/em> or <em>tokenizer<\/em>, and the proper parser. Not all parsers adopt this two-steps schema: some parsers do not depend on a lexer. They are called <em>scannerless parsers<\/em>.<\/p>\n<p>A lexer and a parser work in sequence: the lexer scans the input and produces the matching tokens, the parser scans the tokens and produces the parsing result.<\/p>\n<p>Let\u2019s look at the following example and imagine that we are trying to parse a mathematical operation.<\/p>\n<pre class=\"brush:bash\">437 + 734<\/pre>\n<p>The lexer scans the text and find \u20184\u2019, \u20183\u2019, \u20187\u2019 and then the space \u2018 \u2018. The job of the lexer is to recognize that the first characters constitute one token of type <em>NUM.<\/em> Then the lexer finds a \u2018+\u2019 symbol, which corresponds to a second token of type <em>PLUS<\/em>, and lastly it finds another token of type <em>NUM<\/em>.<a href=\"http:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2017\/07\/lexer-parser-center.png\"><img decoding=\"async\" class=\"aligncenter wp-image-17980\" src=\"http:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2017\/07\/lexer-parser-center.png\" alt=\"\" width=\"860\" height=\"156\" srcset=\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2017\/07\/lexer-parser-center.png 1030w, https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2017\/07\/lexer-parser-center-300x54.png 300w, https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2017\/07\/lexer-parser-center-768x139.png 768w, https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2017\/07\/lexer-parser-center-1024x186.png 1024w\" sizes=\"(max-width: 860px) 100vw, 860px\" \/><\/a><\/p>\n<p>The parser will typically combine the tokens produced by the lexer and group them.<\/p>\n<p>The definitions used by lexers or parser are called <em>rules<\/em> or <em>productions<\/em>. A lexer rule will specify that a sequence of digits correspond to a token of type <em>NUM<\/em>, while a parser rule will specify that a sequence of tokens of type <em>NUM, PLUS, NUM <\/em>corresponds to an expression.<\/p>\n<p><strong>Scannerless parsers<\/strong> are different because they process directly the original text, instead of processing a list of tokens produced by a lexer.<\/p>\n<p>It is now typical to find suites that can generate both a lexer and parser. In the past it was instead more common to combine two different tools: one to produce the lexer and one to produce the parser. This was for example the case of the venerable lex &amp; yacc couple: lex produced the lexer, while yacc produced the parser.<\/p>\n<h3>Parse Tree And Abstract Syntax Tree<\/h3>\n<p>There are two terms that are related and sometimes they are used interchangeably: parse tree and Abstract SyntaxTree (AST).<\/p>\n<p>Conceptually they are very similar:<\/p>\n<ul>\n<li>they are both <strong>trees<\/strong>: there is a root representing the whole piece of code parsed. Then there are smaller subtrees representing portions of code that become smaller until single tokens appear in the tree<\/li>\n<li>the difference is the level of abstraction: the parse tree contains all the tokens which appeared in the program and possibly a set of intermediate rules. The AST instead is a polished version of the parse tree where the information that could be derived or is not important to understand the piece of code is removed<\/li>\n<\/ul>\n<p>In the AST some information is lost, for instance comments and grouping symbols (parentheses) are not represented. Things like comments are superfluous for a program and grouping symbols are implicitly defined by the structure of the tree.<\/p>\n<p>A parse tree is a representation of the code closer to the concrete syntax. It shows many details of the implementation of the parser. For instance, usually a rules correspond to the type of a node. They are usually transformed in AST by the user, with some help from the parser generator.<\/p>\n<p>A graphical representation of an AST looks like this.<\/p>\n<p><a href=\"http:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2017\/07\/798px-Abstract_syntax_tree_for_Euclidean_algorithm.svg_.png\"><img decoding=\"async\" class=\"aligncenter size-full wp-image-17981\" src=\"http:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2017\/07\/798px-Abstract_syntax_tree_for_Euclidean_algorithm.svg_.png\" alt=\"\" width=\"798\" height=\"900\" srcset=\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2017\/07\/798px-Abstract_syntax_tree_for_Euclidean_algorithm.svg_.png 798w, https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2017\/07\/798px-Abstract_syntax_tree_for_Euclidean_algorithm.svg_-266x300.png 266w, https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2017\/07\/798px-Abstract_syntax_tree_for_Euclidean_algorithm.svg_-768x866.png 768w\" sizes=\"(max-width: 798px) 100vw, 798px\" \/><\/a><\/p>\n<p>&nbsp;<\/p>\n<p>Sometimes you may want to start producing a parse tree and then derive from it an AST. This can make sense because the parse tree is easier to produce for the parser (it is a direct representation of the parsing process) but the AST is simpler and easier to process by the following steps. By following steps we mean all the operations that you may want to perform on the tree: code validation, interpretation, compilation, etc..<\/p>\n<h3>Grammar<\/h3>\n<blockquote><p>A grammar is a formal description of a language that can be used to recognize its structure.<\/p><\/blockquote>\n<p>In simple terms is a list of rules that define how each construct can be composed. For example, a rule for an if statement could specify that it must starts with the \u201cif\u201d keyword, followed by a left parenthesis, an expression, a right parenthesis and a statement.<\/p>\n<p>A rule could reference other rules or token types. In the example of the if statement, the keyword \u201cif\u201d, the left and the right parenthesis were token types, while expression and statement were references to other rules.<\/p>\n<p>The most used format to describe grammars is the <strong>Backus-Naur Form (BNF)<\/strong>, which also has many variants, including the <strong>Extended Backus-Naur Form<\/strong>. The Extended variant has the advantage of including a simple way to denote repetitions. A typical rule in a Backus-Naur grammar looks like this:<\/p>\n<pre class=\"brush:bash\">&lt;symbol&gt; ::= __expression__<\/pre>\n<p>The <code>&lt;simbol&gt;<\/code> is usually nonterminal, which means that it can be replaced by the group of elements on the right, <code>__expression__<\/code>. The element <code>__expression__<\/code> could contains other nonterminal symbols or terminal ones. Terminal symbols are simply the ones that do not appear as a <code>&lt;symbol&gt;<\/code> anywhere in the grammar. A typical example of a terminal symbol is a string of characters, like \u201cclass\u201d.<\/p>\n<h3>Left-recursive Rules<\/h3>\n<p>In the context of parsers an important feature is the support for left-recursive rules. This means that a rule could start with a reference to itself. This reference could be also indirect.<\/p>\n<p>Consider for example arithmetic operations. An addition could be described as two expression(s) separated by the plus (+) symbol, but an expression could also contain other additions.<\/p>\n<pre class=\"brush:bash\">addition       ::= expression '+' expression\r\nmultiplication ::= expression '*' expression\r\n\/\/ an expression could be an addition or a multiplication or a number\r\nexpression     ::= addition | multiplication |\/\/ a number<\/pre>\n<p>This description also match multiple additions like 5 + 4 + 3. That is because it can be interpreted as expression (5) (\u2018+\u2019) expression(4+3). And then 4 + 3 itself can be divided in its two components.<\/p>\n<p>The problem is that this kind of rules may not be used with some parser generators. The alternative is a long chain of expressions that takes care also of the precedence of operators.<\/p>\n<p>Some parser generators support direct left-recursive rules, but not indirect one.<\/p>\n<h3>Types Of Languages And Grammars<\/h3>\n<p>We care mostly about two types of languages that can be parsed with a parser generator:<em> regular languages<\/em> and <em>context-free language<\/em>s. We could give you the formal definition according to the <a href=\"https:\/\/en.wikipedia.org\/wiki\/Chomsky_hierarchy\">Chomsky hierarchy of languages<\/a>, but it would not be that useful. Let\u2019s look at some practical aspects instead.<\/p>\n<p>A regular language can be defined by a series of regular expressions, while a context-free one need something more. A simple rule of thumb is that if a grammar of a language has recursive elements it is not a regular language. For instance, as we said elsewhere, <a href=\"https:\/\/www.javacodegeeks.com\/2017\/03\/antlr-mega-tutorial.html\">HTML is not a regular language<\/a>. In fact, most programming languages are context-free languages.<\/p>\n<p>Usually to a kind of language correspond the same kind of grammar. That is to say there are regular grammars and context-free grammars that corresponds respectively to regular and context-free languages. But to complicate matters, there is a relatively new (created in 2004) kind of grammar, called Parsing Expression Grammar (PEG). These grammars are as powerful as Context-free grammars, but according to their authors they describe more naturally programming languages.<\/p>\n<h3>The Differences Between PEG and CFG<\/h3>\n<p>The main difference between PEG and CFG is that the ordering of choices is meaningful in PEG, but not in CFG. If there are many possible valid ways to parse an input, a CFG will be ambiguous and thus wrong. Instead with PEG the first applicable choice will be chosen, and this automatically solve some ambiguities.<\/p>\n<p>Another difference is that PEG use scannerless parsers: they do not need a separate lexer, or lexical analysis phase.<\/p>\n<p>Traditionally both PEG and some CFG have been unable to deal with left-recursive rules, but some tools have found workarounds for this. Either by modifying the basic parsing algorithm, or by having the tool automatically rewrite a left-recursive rule in a non recursive way. Either of these ways has downsides: either by making the generated parser less intelligible or by worsen its performance. However, in practical terms, the advantages of easier and quicker development outweigh the drawbacks.<\/p>\n<h2>Parser Generators<\/h2>\n<p>The basic workflow of a parser generator tool is quite simple: you write a grammar that defines the language, or document, and you run the tool to generate a parser usable from your JavaScript code.<\/p>\n<p>The parser might produce the AST, that you may have to traverse yourself or you can traverse with additional ready-to-use classes, such <a href=\"https:\/\/en.wikipedia.org\/wiki\/Observer_pattern\">Listeners<\/a> or <a href=\"https:\/\/en.wikipedia.org\/wiki\/Visitor_pattern\">Visitors<\/a>. Some tools instead offer the chance to embed code inside the grammar to be executed every time the specific rule is matched.<\/p>\n<p>Usually you need a runtime library and\/or program to use the generated parser.<\/p>\n<h3>Regular (Lexer)<\/h3>\n<p>Tools that analyze regular languages are typically lexers.<\/p>\n<h3>Lexer<\/h3>\n<p><a href=\"https:\/\/github.com\/aaditmshah\/lexer\">Lexer<\/a> is a lexer that claims to be modelled after flex. Though a more fair description would be a short lexer based upon <code>RegExp<\/code>. The documentation seems minimal, with just a few examples, but the whole thing is 147 lines of code, so it is actually comprehensive.<\/p>\n<p>However in a few lines manages to support a few interesting things and it appears to be quite popular and easy to use. One thing is its supports <a href=\"https:\/\/ringojs.org\/\">RingoJS<\/a>, a JavaScript platform on top of the JVM. Another one is the integration with Jison, the Bison clone in JavaScript. If you temper your expectations it can be an useful tool.<\/p>\n<p>There is no grammar, you just use a function to define the RegExp pattern and the action that should be executed when the pattern is matched. So it is a cross between a lexer generator and a lexer combinator. You cannot combine different lexer functions, like in a lexer combinator, but the lexer it is only created dynamically at runtime, so it is not a proper lexer generator either.<\/p>\n<p>A lexer example<\/p>\n<pre class=\"brush:js\">var lexer = new Lexer;\r\n \r\nvar chars = lines = 0;\r\n \r\nlexer.addRule(\/\\n\/, function () {\r\n    lines++;\r\n    chars++;\r\n});\r\n    \r\nlexer.addRule(\/.\/, function () {\r\n    chars++;\r\n});\r\n    \r\nlexer.setInput(\"Hello World!\\n Hello Stars!\\n!\")\r\n    \r\nlexer.lex();<\/pre>\n<h3>Context Free<\/h3>\n<p>Let\u2019s see the tools that generate Context Free parsers.<\/p>\n<h3>ANTLR<\/h3>\n<p><a href=\"http:\/\/www.antlr.org\/\">ANTLR<\/a> is a great parser generator written in Java that can also generate parsers for JavaScript and many other languages. There is also a <a href=\"https:\/\/github.com\/tunnelvisionlabs\/antlr4ts\">beta version for TypeScript<\/a> from the same guy that makes the <em>optimized C#<\/em> version. ANTLR is based on an new LL algorithm developed by the author and described in this paper: <a href=\"http:\/\/www.antlr.org\/papers\/allstar-techreport.pdf\">Adaptive LL(*) Parsing: The Power of Dynamic Analysis (PDF)<\/a>.<\/p>\n<p>It is quite popular for its many useful features: for instance version 4 supports direct left-recursive rules. However a real added value of a vast community it is the<a href=\"https:\/\/github.com\/antlr\/grammars-v4\"> large amount of grammars available<\/a>.<\/p>\n<p>It provides two ways to walk the AST, instead of embedding actions in the grammar: visitors and listeners. The first one is suited when you have to manipulate or interact with the elements of the tree, while the second is useful when you just have to do something when a rule is matched.<\/p>\n<p>The typical grammar is divided in two parts: lexer rules and parser rules. The division is implicit, since all the rules starting with an uppercase letter are lexer rules, while the ones starting with a lowercase letter are parser rules. Alternatively lexer and parser grammars can be defined in separate files.<\/p>\n<p>A very simple ANTLR grammar<\/p>\n<pre class=\"brush:bash\">grammar simple;\r\n \r\nbasic   : NAME ':' NAME ;\r\n \r\nNAME    : [a-zA-Z]* ;\r\n \r\nCOMMENT : '\/*' .*? '*\/' -&gt; skip ;<\/pre>\n<p>If you are interested in ANTLR you can look into this giant <a href=\"https:\/\/www.javacodegeeks.com\/2017\/03\/antlr-mega-tutorial.html\">ANTLR tutorial<\/a> we have written.<\/p>\n<h3>APG<\/h3>\n<p><a href=\"http:\/\/www.coasttocoastresearch.com\/overview\">APG<\/a> is a recursive-descent parser using a variation of <strong>Augmented BNF<\/strong>, that they call Superset Augmented BNF. ABNF is a particular variant of BNF designed to better support bidirectional communications protocol. APG also support additional operators, like syntactic predicates and custom user defined matching functions.<\/p>\n<p>It can generate parsers in C\/C++, Java e JavaScript. Support for the last language seems superior and more up to date: it has a few more features and seems more updated. In fact the documentation says it is designed to have the look and feel of JavaScript RegExp.<\/p>\n<p>Because it is based on ABNF, it is especially well suited to parsing the languages of many Internet technical specifications and, in fact, is the parser of choice for a number of large Telecom companies.<\/p>\n<p>An APG grammar is very clean and easy to understand.<\/p>\n<pre class=\"brush:bash\">\/\/ example from a tutorial of the author of the tool available here\r\n\/\/ https:\/\/www.sitepoint.com\/alternative-to-regular-expressions\/\r\nphone-number = [\"(\"] area-code sep office-code sep subscriber\r\narea-code    = 3digit                       ; 3 digits\r\noffice-code  = 3digit                       ; 3 digits\r\nsubscriber   = 4digit                       ; 4 digits\r\nsep          = *3(%d32-47 \/ %d58-126 \/ %d9) ; 0-3 ASCII non-digits\r\ndigit        = %d48-57                      ; 0-9<\/pre>\n<h3>Jison<\/h3>\n<blockquote><p><a href=\"http:\/\/zaa.ch\/jison\/\">Jison<\/a> generates bottom-up parsers in JavaScript. Its API is similar to Bison\u2019s, hence the name.<\/p><\/blockquote>\n<p>Despite the name Jison can also replace flex, so you do not need a separate lexer. Although you can use one or build your own custom lexer. All you need is an object with the functions <code>setInput<\/code> and <code>lex<\/code>. It can best recognize languages described by LALR(1) grammars, though it also has modes for LR(0), SLR(1).<\/p>\n<p>The generated parser does not require a runtime component, you can use it as a standalone software.<\/p>\n<p>It has a good enough documentation with a few examples and even a section to try your grammars online. Although at times it relies on the Bison manual to cover the lacks of its own documentation.<\/p>\n<p>A Jison grammar can be inputted using a custom JSON fornat or a Bison-styled one. Both requires you to use embedded actions if you want to do something when a rule is matched. The following example is in the custom JSON format.<\/p>\n<pre class=\"brush:bash\">\/\/ example from the documentation\r\n{\r\n   \"comment\": \"JSON Math Parser\",\r\n   \/\/ JavaScript comments also work\r\n \r\n   \"lex\": {\r\n      \"rules\": [\r\n         [\"\\\\s+\",                    \"\/* skip whitespace *\/\"],\r\n         [\"[0-9]+(?:\\\\.[0-9]+)?\\\\b\", \"return 'NUMBER'\"],\r\n         [\"\\\\*\",                     \"return '*'\"],\r\n         [\"\\\\\/\",                     \"return '\/'\"],\r\n         [\"-\",                       \"return '-'\"],\r\n         [\"\\\\+\",                     \"return '+'\"],\r\n         [..] \/\/ skipping some parts\r\n      ]\r\n   },\r\n \r\n   \"operators\": [\r\n      [\"left\", \"+\", \"-\"],\r\n      [\"left\", \"*\", \"\/\"],\r\n      [\"left\", \"UMINUS\"]\r\n      [..] \/\/ skipping some parts\r\n   ],\r\n \r\n   \"bnf\": {\r\n      \"expressions\": [[\"e EOF\",   \"return $1\"]],\r\n \r\n      \"e\" :[\r\n         [\"e + e\",  \"$$ = $1+$3\"],\r\n         [\"e - e\",  \"$$ = $1-$3\"],  \r\n         [\"- e\",    \"$$ = -$2\", {\"prec\": \"UMINUS\"}],        \r\n         [\"NUMBER\", \"$$ = Number(yytext)\"],\r\n         [..] \/\/ skipping some parts\r\n      ]\r\n   }\r\n}<\/pre>\n<p>It is <a href=\"https:\/\/github.com\/zaach\/jison\/wiki\/ProjectsUsingJison\">very popular<\/a> and used by many project including CoffeeScript and Handlebars.js.<\/p>\n<h3>Nearley<\/h3>\n<blockquote><p><a href=\"http:\/\/nearley.js.org\/\">nearley<\/a> uses the Earley parsing algorithm augmented with Joop Leo\u2019s optimizations to parse complex data structures easily. nearley is \u00fcber-fast and really powerful. It can parse literally anything you throw at it.<\/p><\/blockquote>\n<p>The Earley algorithm is designed to easily handle all grammars, including left-recursive and ambiguous ones. Essentially its main advantage it is that it should never catastrophically fail. On the other hand it could be slower than other parsing algorithms. Nearly itself also is able to detect some ambiguous grammars. It can also and reports multiple results in the case of an ambiguous input.<\/p>\n<p>A Nearley grammar is a written in a <code>.ne<\/code> file that can include custom code. A rule can include an embedded action, which the documentation calls a <em>postprocessing function<\/em>. You can also use a custom lexer.<\/p>\n<pre class=\"brush:bash\"># from the examples in Nearly\r\n# csv.ne\r\n \r\n@{%\r\nvar appendItem = function (a, b) { return function (d) { return d[a].concat([d[b]]); } };\r\nvar appendItemChar = function (a, b) { return function (d) { return d[a].concat(d[b]); } };\r\nvar empty = function (d) { return []; };\r\nvar emptyStr = function (d) { return \"\"; };\r\n%}\r\n \r\n \r\nfile              -&gt; header newline rows             {% function (d) { return { header: d[0], rows: d[2] }; } %}\r\n# id is a special preprocessor function that return the first token in the match\r\nheader            -&gt; row                             {% id %}\r\n \r\nrows              -&gt; row\r\n                   | rows newline row                {% appendItem(0,2) %}\r\n \r\nrow               -&gt; field\r\n                   | row \",\" field                   {% appendItem(0,2) %}\r\n \r\nfield             -&gt; unquoted_field                  {% id %}\r\n                   | \"\\\"\" quoted_field \"\\\"\"          {% function (d) { return d[1]; } %}\r\n \r\nquoted_field      -&gt; null                            {% emptyStr %}\r\n                   | quoted_field quoted_field_char  {% appendItemChar(0,1) %}\r\n \r\nquoted_field_char -&gt; [^\"]                            {% id %}\r\n                   | \"\\\"\" \"\\\"\"                       {% function (d) { return \"\\\"\"; } %}\r\n \r\nunquoted_field    -&gt; null                            {% emptyStr %}\r\n                   | unquoted_field char             {% appendItemChar(0,1) %}\r\n \r\nchar              -&gt; [^\\n\\r\",]                       {% id %}\r\n \r\nnewline           -&gt; \"\\r\" \"\\n\"                       {% empty %}ca\r\n                   | \"\\r\" | \"\\n\"                     {% empty %}<\/pre>\n<p>Another interesting feature is that you could build custom tokens. You can define them using a tokenizing library, a literal or a test function. The test function must return true if the text correspond to that specific token.<\/p>\n<p>Custom tokens example<\/p>\n<pre class=\"brush:js\">@{%\r\nvar print_tok  = {literal: \"print\"};\r\nvar number_tok = {test: function(x) {return x.constructor === Number; }}\r\n%}\r\n \r\n \r\nmain -&gt; %print_tok %number_tok<\/pre>\n<p>Nearley include tools for debugging and understanding your parser. For instance Unparser can automatically generate random strings that are considered correct by your parser. This is useful to test your parser against random noise or even to generate data from a schema (e.g. a random email address). It also include a tool to generate SVG <a href=\"https:\/\/en.wikipedia.org\/wiki\/Syntax_diagram\">railroad diagrams<\/a>: a graphical way to represent a grammar.<\/p>\n<p><a href=\"http:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2017\/07\/railroad_example.png\"><img decoding=\"async\" class=\"aligncenter size-full wp-image-17982\" src=\"http:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2017\/07\/railroad_example.png\" alt=\"\" width=\"689\" height=\"501\" srcset=\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2017\/07\/railroad_example.png 689w, https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2017\/07\/railroad_example-300x218.png 300w\" sizes=\"(max-width: 689px) 100vw, 689px\" \/><\/a><\/p>\n<p>Railroad diagrams from the <a href=\"http:\/\/nearley.js.org\/www\/railroad-demo.html\">documentation demo<\/a><\/p>\n<p>A Nearley parser requires the Nearley runtime.<\/p>\n<p>Nearley documentation is a good overview of what is available and there is also a third-party playground to try a grammar online. But you will not find a complete explanation of all the features.<\/p>\n<h3>PEG<\/h3>\n<p>After the CFG parsers is time to see the PEG parsers available for JavaScript.<\/p>\n<h3>Canopy<\/h3>\n<blockquote><p><a href=\"http:\/\/canopy.jcoglan.com\/\">Canopy<\/a> is a parser compiler targeting Java, JavaScript, Python and Ruby. It takes a file describing a parsing expression grammar and compiles it into a parser module in the target language. The generated parsers have no runtime dependency on Canopy itself.<\/p><\/blockquote>\n<p>It also provides easy access to the parse tree nodes.<\/p>\n<p>A Canopy grammar has the neat feature of using actions annotation to use custom code in the parser. In practical terms. you just write the name of a function next to a rule and then you implement the function in your source code.<\/p>\n<p>A Canopy grammar with actions<\/p>\n<pre class=\"brush:bash\">\/\/ the actions are prepended by %\r\ngrammar Maps\r\n  map     &lt;-  \"{\" string \":\" value \"}\" %make_map\r\n  string  &lt;-  \"'\" [^']* \"'\" %make_string\r\n  value   &lt;-  list \/ number\r\n  list    &lt;-  \"[\" value (\",\" value)* \"]\" %make_list\r\n  number  &lt;-  [0-9]+ %make_number<\/pre>\n<p>The JavaScript file containing the action code.<\/p>\n<pre class=\"brush:js\">var maps = require('.\/maps');\r\n \r\nvar actions = {\r\n  make_map: function(input, start, end, elements) {\r\n    var map = {};\r\n    map[elements[1]] = elements[3];\r\n    return map;\r\n  },\r\n  [..]\r\n};<\/pre>\n<h3>Ohm<\/h3>\n<blockquote><p>Ohm is a parser generator consisting of a library and a domain-specific language<\/p><\/blockquote>\n<p>Ohm grammars are defined in a custom format that can be put in a separate file or in a string. However the parser is generate dynamically and not with a separate tool. In that sense it works like a parser library more than a traditional parser generator.<\/p>\n<p>An helper function to create an AST is included among the extras.<\/p>\n<blockquote><p>In Ohm, a grammar defines a language, and semantic actions specify what to do with valid inputs in that language<\/p><\/blockquote>\n<p>A grammar is completely separated from semantic actions. This simplify portability and readbility and allows to support different languages with the same grammar. At the moment Ohm only supports JavaScript, but more language are planned for the future. The typical grammar is then clean and readable.<\/p>\n<p>arithmetic.ohm<\/p>\n<pre class=\"brush:bash\">Arithmetic {\r\n  Exp\r\n    = AddExp\r\n \r\n  AddExp\r\n    = AddExp \"+\" PriExp  -- plus\r\n    | AddExp \"-\" PriExp  -- minus\r\n    | PriExp\r\n \r\n  PriExp\r\n    = \"(\" Exp \")\"  -- paren\r\n    | number\r\n \r\n  number\r\n    = digit+\r\n}<\/pre>\n<p>Semantic actions can be implemented using a simple API. In practical terms this ends up working like the visitor pattern with the difference that is easier to define more groups of semantic actions.<\/p>\n<p>Example Ohm semantic actions<\/p>\n<p>JavaScript<\/p>\n<pre class=\"brush:js\">var semantics = g.createSemantics().addOperation('eval', {\r\n  Exp: function(e) {\r\n    return e.eval();\r\n  },\r\n  AddExp: function(e) {\r\n    return e.eval();\r\n  },\r\n  AddExp_plus: function(left, op, right) {\r\n    return left.eval() + right.eval();\r\n  },\r\n  AddExp_minus: function(left, op, right) {\r\n    return left.eval() - right.eval();\r\n  },\r\n  PriExp: function(e) {\r\n    return e.eval();\r\n  },\r\n  PriExp_paren: function(open, exp, close) {\r\n    return exp.eval();\r\n  },\r\n  number: function(chars) {\r\n    return parseInt(this.sourceString, 10);\r\n  },\r\n});\r\nvar match = g.match('1 + (2 - 3) + 4');\r\nconsole.log(semantics(match).eval());<\/pre>\n<p>To support debugging Ohm has a text trace and (work in progress) graphical visualizer. You can see the graphical visualizer at work and test a grammar in the <a href=\"https:\/\/ohmlang.github.io\/editor\/\">interactive editor<\/a>.<\/p>\n<p>The documentation is not that bad, though you have to go under the <code>doc<\/code> directory to find it. There is no tutorial, but there are a few examples and a reference. In particular the documentation suggests reading a well commented <a href=\"https:\/\/github.com\/harc\/ohm\/blob\/master\/examples\/math\/index.html\">Math example<\/a>.<\/p>\n<h3>PEG.js<\/h3>\n<blockquote><p>PEG.js is a simple parser generator for JavaScript that produces fast parsers with excellent error reporting.<\/p><\/blockquote>\n<p>PEG.js can work as a traditional parser generator and create a parser with a tool or can generate one using a grammar defined in the code. It supports different module loaders (e.g. AMD, CommonJS, etc.).<\/p>\n<p>PEG.js has a neat online editor that allows to write a grammar, test the generated parser and download it.<\/p>\n<p>A PEG.js grammar is usually written in a <code>.pegjs<\/code> file and can include embedded actions, custom initializing code and semantic predicates. That is to say functions that determine if a specific match is activated or not.<\/p>\n<p>Example math.pegjs grammar<\/p>\n<pre class=\"brush:bash\">\/\/ example from the documentation\r\n{\r\n  function makeInteger(o) {\r\n    return parseInt(o.join(\"\"), 10);\r\n  }\r\n}\r\n \r\nstart\r\n  = additive\r\n \r\nadditive\r\n  = left:multiplicative \"+\" right:additive { return left + right; }\r\n  \/ multiplicative\r\n \r\nmultiplicative\r\n  = left:primary \"*\" right:multiplicative { return left * right; }\r\n  \/ primary\r\n \r\nprimary\r\n  = integer\r\n  \/ \"(\" additive:additive \")\" { return additive; }\r\n \r\ninteger \"integer\"\r\n  = digits:[0-9]+ { return makeInteger(digits); }<\/pre>\n<p>The documentation is good enough, there are a few example grammars, but there are no tutorials available. The popularity of the project had led to the development of third-party <a href=\"https:\/\/github.com\/pegjs\/pegjs\/wiki\/Tools\">tools<\/a>, like one to generate railroad diagrams, and <a href=\"https:\/\/github.com\/pegjs\/pegjs\/wiki\/Plugins\">plugins<\/a>, like one to generate TypeScrypt parsers.<\/p>\n<h3>Waxeye<\/h3>\n<blockquote><p><a href=\"https:\/\/waxeye.org\/\">Waxeye<\/a> is a parser generator based on parsing expression grammars (PEGs). It supports C, Java, Javascript, Python, Ruby and Scheme.<\/p><\/blockquote>\n<p>Waxeye can facilitate the creation of an AST by defining nodes in the grammar that will not be included in the generated tree. That is quite useful, but a drawback of Waxeye is that it only generate a AST. In the sense that there is no way to automatically execute an action when you match a node. You have to traverse and execute what you need manually.<\/p>\n<p>One positive side-effect of this limiation is that grammars are easily readable and clean. They are also independent from any language.<\/p>\n<p>Calc.waxeye<\/p>\n<pre class=\"brush:bash\">\/\/ from the manual\r\n \r\ncalc  &lt;- ws sum\r\n \r\nsum   &lt;- prod *([+-] ws prod)\r\n \r\nprod  &lt;- unary *([*\/] ws unary)\r\n \r\nunary &lt;= '-' ws unary\r\n       | :'(' ws sum :')' ws\r\n       | num\r\n \r\nnum   &lt;- +[0-9] ?('.' +[0-9]) ws\r\n \r\nws    &lt;: *[ \\t\\n\\r]<\/pre>\n<p>A particular feature of Waxeye is that it provides some help to compose different grammars together and then it facilitate modularity. For instance you could create a common grammar for identifiers, that are usually similar in many languages.<\/p>\n<p>Waxeye has a great documentation in the form of a manual that explains basic concepts and how to use the tool for all the languages it supports. There are a few example grammars.<\/p>\n<h2>Parser Combinators<\/h2>\n<p>They allow you to create a parser simply with JavaScript code, by combining different pattern matching functions, that are equivalent to grammar rules. They are generally considered suited for simpler parsing needs. Given they are just JavaScript libraries you can easily introduce them into your project: you do not need any specific generation step and you can write all of your code in your favorite editor. Their main advantage is the possibility of being integrated in your traditional workflow and IDE.<\/p>\n<p>In practice this means that they are very useful for all the little parsing problems you find. If the typical developer encounter a problem, that is too complex for a simple regular expression, these libraries are usually the solution. In short, if you need to build a parser, but you don\u2019t actually want to, a parser combinator may be your best option.<\/p>\n<h3>Bennu, Parjs And Parsimmon<\/h3>\n<blockquote><p>Bennu is a Javascript parser combinator library based on Parsec. The Bennu library consists of a core set of parser combinators that implement <a href=\"https:\/\/github.com\/fantasyland\/fantasy-land\">Fantasy Land interfaces<\/a>. More advanced functionality such as detailed error messaging, custom parser state, memoization, and running unmodified parsers incrementally is also supported.<\/p><\/blockquote>\n<p>All libraries are inspired by Parsec. Bennu and Parsimmon are the oldest and Bennu the more advanced between the two. They also all have an extensive documentation, but they have is no tutorial.<\/p>\n<p>An example from the documentation.<\/p>\n<p>Bennu example<\/p>\n<pre class=\"brush:js\">var parse = require('bennu').parse;\r\nvar text = require('bennu').text;\r\n \r\nvar aOrB = parse.either(\r\n    text.character('a'),\r\n    text.character('b'));\r\n \r\nparse.run(aOrB, 'b'); \/\/ 'b'<\/pre>\n<blockquote><p>Parsimmon is a small library for writing big parsers made up of lots of little parsers. The API is inspired by parsec and Promises\/A+.<\/p><\/blockquote>\n<p>Parsimmon is the most popular among the three, it is stable and updated.<\/p>\n<p>The following is a part of the JSON example.<\/p>\n<p>Parsimmon JSON example<\/p>\n<pre class=\"brush:js\">let whitespace = P.regexp(\/\\s*\/m);\r\n \r\nlet JSONParser = P.createLanguage({\r\n  \/\/ This is the main entry point of the parser: a full JSON value.\r\n  value: r =&gt;\r\n    P.alt(\r\n      r.object,\r\n      r.string,\r\n      [..]\r\n    ).thru(parser =&gt; whitespace.then(parser)),\r\n \r\n  [..]\r\n \r\n  \/\/ Regexp based parsers should generally be named for better error reporting.\r\n  string: () =&gt;\r\n    token(P.regexp(\/\"((?:\\\\.|.)*?)\"\/, 1))\r\n      .map(interpretEscapes)\r\n      .desc('string'),\r\n \r\n  [..]\r\n \r\n  object: r =&gt;\r\n    r.lbrace\r\n      .then(r.pair.sepBy(r.comma))\r\n      .skip(r.rbrace)\r\n      .map(pairs =&gt; {\r\n        let object = {};\r\n        pairs.forEach(pair =&gt; {\r\n          let [key, value] = pair;\r\n          object[key] = value;\r\n        });\r\n        return object;\r\n      }),\r\n});\r\n \r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n \r\nlet text = \/\/ JSON Object\r\n \r\nlet ast = JSONParser.value.tryParse(text);<\/pre>\n<blockquote><p>Parjs is a JavaScript library of parser combinators, similar in principle and in design to the likes of Parsec and in particular its F# adaptation <a href=\"http:\/\/www.quanttec.com\/fparsec\/\">FParsec<\/a>.<\/p>\n<p>It\u2019s also similar to the parsimmon library, but intends to be superior to it.<\/p><\/blockquote>\n<p>Parjs is only a few months old, but it is already quite developed. It also have the advantage of begin written int TypeScript.<\/p>\n<p>All the libraries have good documentation, but Parjs is great: it explained how to use the parser and also how to design good parsers with it. There are a few examples, including the following on string formatting.<\/p>\n<p>Parjs String Format example<\/p>\n<pre class=\"brush:js\">\/**\r\n * Created by lifeg on 04\/04\/2017.\r\n *\/\r\nimport \"..\/setup\";\r\nimport {Parjs, LoudParser} from \"..\/src\";\r\n\/\/+ DEFINING THE PARSER\r\n \r\n\/\/Parse an identifier, an asciiLetter followed by an asciiLetter or digit, e.g. a12b but not 1ab.\r\nlet ident = Parjs.letter.then(Parjs.letter.or(Parjs.digit).many()).str;\r\n \r\n\/\/Parse a format token, an `ident` between `{` and `}`. Return the result as a Token object.\r\nlet formatToken = ident.between(Parjs.string(\"{\"), Parjs.string(\"}\")).map(x =&gt; ({token: x}));\r\n \r\n\/\/Parse an escaped character. This parses \"`{a}\" as the text \"{a}\" instead of a token.\r\n\/\/Also escapes the escaped char, parsing \"``\" as \"`\".\r\n\/\/Works for arbitrary characters like `a being parsed as a.\r\nlet escape = Parjs.string(\"`\").then(Parjs.anyChar).str.map(x =&gt; ({text: x.substr(1)}));\r\n \r\n\/\/Parse text which is not an escape character or {.\r\nlet text = Parjs.noCharOf(\"`{\").many(1).str.map(x =&gt; ({text: x}));\r\n \r\n\/\/The parser itself. Parses either a formatToken, e.g. {abc} or an escaped combo `x, or text that doesn't contain `{.\r\n\/\/Parses many times.\r\nlet formatParser = formatToken.or(escape, text).many();\r\n \r\n\/\/This prints a sequence of tokens {text: \"hello, my name is \"}, {token: name}, {text: \" and I am \"}, {token: \" years old}, ...\r\nconsole.log(formatParser.parse(\"hello, my name is {name} and I am {age} years old. This is `{escaped}. This is double escaped: ``{name}.\"));<\/pre>\n<h2>JavaScript Libraries That Parse JavaScript<\/h2>\n<p>There is one special case that could be managed in more specific way: the case in which you want to parse JavaScript code in JavaScript. Contrary to what we have found for Java and C# there is not a definitive choice: there are many good choices to parse JavaScript.<\/p>\n<p>The three most popular libraries seems to be: <a href=\"https:\/\/github.com\/ternjs\/acorn\">Acorn<\/a>, <a href=\"https:\/\/github.com\/jquery\/esprima\">Esprima<\/a> and <a href=\"https:\/\/github.com\/mishoo\/UglifyJS2\">UglifyJS<\/a>. We are not going to say which one it is best because they all seem to be awesome, updated and well supported.<\/p>\n<p>One important difference is that UglifyJS is also a mangler\/compressor\/beautifier toolkit, which means that it also has many other uses. On the other hand it is the only one to support only up to the version ECMAScript 5. Another thing to consider is that only esprima have a documentation worthy of projects of such magnitude.<\/p>\n<h2>Summary<\/h2>\n<p>As we said in the sisters article about parsing in Java and C#, the world of parsers is a bit different from the usual world of programmers. In the case of JavaScript also the language lives in a different world from any other programming language. There is such disparate level of competence between its developers that you could find the best ones working with people that just barely know how to put together a script. And both want to parse things.<\/p>\n<p>So for JavaScript there are tools that a bit all over this spectrum. We have serious tools developed by academics for their courses or in the course of their degrees together with much simpler tools. Some of which blur the lines between parser generators and parser combinators. And all of them have their place. A further complication is that while usually parser combinators are reserved for easier uses, with JavaScript it is not always the case. You could find very powerful and complex parser combinators and much easier parser generators.<\/p>\n<p>So with JavaScript more than ever we cannot definitely suggests one software over the other. What it is best for a user might not be the best for somebody else. And we all know that the most technically correct solution might not be ideal in real life with all its constraints. So we wanted to share what we have learned on the best options for parsing in JavaScript.<\/p>\n<div class=\"attribution\">\n<table>\n<tbody>\n<tr>\n<td><span class=\"reference\">Reference: <\/span><\/td>\n<td><a href=\"https:\/\/tomassetti.me\/parsing-in-javascript\/\">Parsing in JavaScript: Tools and Libraries<\/a> from our <a href=\"http:\/\/www.webcodegeeks.com\/join-us\/wcg\/\">WCG partner<\/a> Federico Tomassetti at the <a href=\"http:\/\/tomassetti.me\/\">Federico Tomassetti<\/a> blog.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>This is an article similar to a previous one we wrote: Parsing in Java, so the introduction is the same. Skip to chapter 3 if you have already read it. If you need to parse a language, or document, from JavaScript there are fundamentally three ways to solve the problem: use an existing library supporting &hellip;<\/p>\n","protected":false},"author":149,"featured_media":920,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[9],"tags":[],"class_list":["post-17974","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-javascript"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Parsing in JavaScript: Tools and Libraries - Web Code Geeks - 2026<\/title>\n<meta name=\"description\" content=\"This is an article similar to a previous one we wrote: Parsing in Java, so the introduction is the same. Skip to chapter 3 if you have already read it. If\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.webcodegeeks.com\/javascript\/parsing-javascript-tools-libraries\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Parsing in JavaScript: Tools and Libraries - Web Code Geeks - 2026\" \/>\n<meta property=\"og:description\" content=\"This is an article similar to a previous one we wrote: Parsing in Java, so the introduction is the same. Skip to chapter 3 if you have already read it. If\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.webcodegeeks.com\/javascript\/parsing-javascript-tools-libraries\/\" \/>\n<meta property=\"og:site_name\" content=\"Web Code Geeks\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/webcodegeeks\" \/>\n<meta property=\"article:published_time\" content=\"2017-07-24T09:15:45+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/10\/js-logo.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"150\" \/>\n\t<meta property=\"og:image:height\" content=\"150\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Federico Tomassetti\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@raindancer\" \/>\n<meta name=\"twitter:site\" content=\"@webcodegeeks\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Federico Tomassetti\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"27 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/www.webcodegeeks.com\/javascript\/parsing-javascript-tools-libraries\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/javascript\/parsing-javascript-tools-libraries\/\"},\"author\":{\"name\":\"Federico Tomassetti\",\"@id\":\"https:\/\/www.webcodegeeks.com\/#\/schema\/person\/4d63f143f3c969ad223bc081c0284951\"},\"headline\":\"Parsing in JavaScript: Tools and Libraries\",\"datePublished\":\"2017-07-24T09:15:45+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/javascript\/parsing-javascript-tools-libraries\/\"},\"wordCount\":4442,\"commentCount\":2,\"publisher\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/javascript\/parsing-javascript-tools-libraries\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/10\/js-logo.jpg\",\"articleSection\":[\"JavaScript\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/www.webcodegeeks.com\/javascript\/parsing-javascript-tools-libraries\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.webcodegeeks.com\/javascript\/parsing-javascript-tools-libraries\/\",\"url\":\"https:\/\/www.webcodegeeks.com\/javascript\/parsing-javascript-tools-libraries\/\",\"name\":\"Parsing in JavaScript: Tools and Libraries - Web Code Geeks - 2026\",\"isPartOf\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/javascript\/parsing-javascript-tools-libraries\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/javascript\/parsing-javascript-tools-libraries\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/10\/js-logo.jpg\",\"datePublished\":\"2017-07-24T09:15:45+00:00\",\"description\":\"This is an article similar to a previous one we wrote: Parsing in Java, so the introduction is the same. Skip to chapter 3 if you have already read it. If\",\"breadcrumb\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/javascript\/parsing-javascript-tools-libraries\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.webcodegeeks.com\/javascript\/parsing-javascript-tools-libraries\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.webcodegeeks.com\/javascript\/parsing-javascript-tools-libraries\/#primaryimage\",\"url\":\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/10\/js-logo.jpg\",\"contentUrl\":\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/10\/js-logo.jpg\",\"width\":150,\"height\":150},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.webcodegeeks.com\/javascript\/parsing-javascript-tools-libraries\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.webcodegeeks.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"JavaScript\",\"item\":\"https:\/\/www.webcodegeeks.com\/category\/javascript\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Parsing in JavaScript: Tools and Libraries\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.webcodegeeks.com\/#website\",\"url\":\"https:\/\/www.webcodegeeks.com\/\",\"name\":\"Web Code Geeks\",\"description\":\"Web Developers Resource Center\",\"publisher\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.webcodegeeks.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/www.webcodegeeks.com\/#organization\",\"name\":\"Exelixis Media P.C.\",\"url\":\"https:\/\/www.webcodegeeks.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.webcodegeeks.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"contentUrl\":\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"width\":864,\"height\":246,\"caption\":\"Exelixis Media P.C.\"},\"image\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/webcodegeeks\",\"https:\/\/x.com\/webcodegeeks\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/www.webcodegeeks.com\/#\/schema\/person\/4d63f143f3c969ad223bc081c0284951\",\"name\":\"Federico Tomassetti\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.webcodegeeks.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/10d3414571edf95f2255d57c9c02759daba20499f6761de9228c1cbbbd2fab6c?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/10d3414571edf95f2255d57c9c02759daba20499f6761de9228c1cbbbd2fab6c?s=96&d=mm&r=g\",\"caption\":\"Federico Tomassetti\"},\"description\":\"Federico has a PhD in Polyglot Software Development. He is fascinated by all forms of software development with a focus on Model-Driven Development and Domain Specific Languages.\",\"sameAs\":[\"http:\/\/tomassetti.me\/\",\"https:\/\/fr.linkedin.com\/in\/federicotomassetti\",\"https:\/\/x.com\/raindancer\"],\"url\":\"https:\/\/www.webcodegeeks.com\/author\/federico-tomassetti\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Parsing in JavaScript: Tools and Libraries - Web Code Geeks - 2026","description":"This is an article similar to a previous one we wrote: Parsing in Java, so the introduction is the same. Skip to chapter 3 if you have already read it. If","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.webcodegeeks.com\/javascript\/parsing-javascript-tools-libraries\/","og_locale":"en_US","og_type":"article","og_title":"Parsing in JavaScript: Tools and Libraries - Web Code Geeks - 2026","og_description":"This is an article similar to a previous one we wrote: Parsing in Java, so the introduction is the same. Skip to chapter 3 if you have already read it. If","og_url":"https:\/\/www.webcodegeeks.com\/javascript\/parsing-javascript-tools-libraries\/","og_site_name":"Web Code Geeks","article_publisher":"https:\/\/www.facebook.com\/webcodegeeks","article_published_time":"2017-07-24T09:15:45+00:00","og_image":[{"width":150,"height":150,"url":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/10\/js-logo.jpg","type":"image\/jpeg"}],"author":"Federico Tomassetti","twitter_card":"summary_large_image","twitter_creator":"@raindancer","twitter_site":"@webcodegeeks","twitter_misc":{"Written by":"Federico Tomassetti","Est. reading time":"27 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.webcodegeeks.com\/javascript\/parsing-javascript-tools-libraries\/#article","isPartOf":{"@id":"https:\/\/www.webcodegeeks.com\/javascript\/parsing-javascript-tools-libraries\/"},"author":{"name":"Federico Tomassetti","@id":"https:\/\/www.webcodegeeks.com\/#\/schema\/person\/4d63f143f3c969ad223bc081c0284951"},"headline":"Parsing in JavaScript: Tools and Libraries","datePublished":"2017-07-24T09:15:45+00:00","mainEntityOfPage":{"@id":"https:\/\/www.webcodegeeks.com\/javascript\/parsing-javascript-tools-libraries\/"},"wordCount":4442,"commentCount":2,"publisher":{"@id":"https:\/\/www.webcodegeeks.com\/#organization"},"image":{"@id":"https:\/\/www.webcodegeeks.com\/javascript\/parsing-javascript-tools-libraries\/#primaryimage"},"thumbnailUrl":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/10\/js-logo.jpg","articleSection":["JavaScript"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.webcodegeeks.com\/javascript\/parsing-javascript-tools-libraries\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.webcodegeeks.com\/javascript\/parsing-javascript-tools-libraries\/","url":"https:\/\/www.webcodegeeks.com\/javascript\/parsing-javascript-tools-libraries\/","name":"Parsing in JavaScript: Tools and Libraries - Web Code Geeks - 2026","isPartOf":{"@id":"https:\/\/www.webcodegeeks.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.webcodegeeks.com\/javascript\/parsing-javascript-tools-libraries\/#primaryimage"},"image":{"@id":"https:\/\/www.webcodegeeks.com\/javascript\/parsing-javascript-tools-libraries\/#primaryimage"},"thumbnailUrl":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/10\/js-logo.jpg","datePublished":"2017-07-24T09:15:45+00:00","description":"This is an article similar to a previous one we wrote: Parsing in Java, so the introduction is the same. Skip to chapter 3 if you have already read it. If","breadcrumb":{"@id":"https:\/\/www.webcodegeeks.com\/javascript\/parsing-javascript-tools-libraries\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.webcodegeeks.com\/javascript\/parsing-javascript-tools-libraries\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.webcodegeeks.com\/javascript\/parsing-javascript-tools-libraries\/#primaryimage","url":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/10\/js-logo.jpg","contentUrl":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/10\/js-logo.jpg","width":150,"height":150},{"@type":"BreadcrumbList","@id":"https:\/\/www.webcodegeeks.com\/javascript\/parsing-javascript-tools-libraries\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.webcodegeeks.com\/"},{"@type":"ListItem","position":2,"name":"JavaScript","item":"https:\/\/www.webcodegeeks.com\/category\/javascript\/"},{"@type":"ListItem","position":3,"name":"Parsing in JavaScript: Tools and Libraries"}]},{"@type":"WebSite","@id":"https:\/\/www.webcodegeeks.com\/#website","url":"https:\/\/www.webcodegeeks.com\/","name":"Web Code Geeks","description":"Web Developers Resource Center","publisher":{"@id":"https:\/\/www.webcodegeeks.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.webcodegeeks.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.webcodegeeks.com\/#organization","name":"Exelixis Media P.C.","url":"https:\/\/www.webcodegeeks.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.webcodegeeks.com\/#\/schema\/logo\/image\/","url":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","contentUrl":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https:\/\/www.webcodegeeks.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/webcodegeeks","https:\/\/x.com\/webcodegeeks"]},{"@type":"Person","@id":"https:\/\/www.webcodegeeks.com\/#\/schema\/person\/4d63f143f3c969ad223bc081c0284951","name":"Federico Tomassetti","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.webcodegeeks.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/10d3414571edf95f2255d57c9c02759daba20499f6761de9228c1cbbbd2fab6c?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/10d3414571edf95f2255d57c9c02759daba20499f6761de9228c1cbbbd2fab6c?s=96&d=mm&r=g","caption":"Federico Tomassetti"},"description":"Federico has a PhD in Polyglot Software Development. He is fascinated by all forms of software development with a focus on Model-Driven Development and Domain Specific Languages.","sameAs":["http:\/\/tomassetti.me\/","https:\/\/fr.linkedin.com\/in\/federicotomassetti","https:\/\/x.com\/raindancer"],"url":"https:\/\/www.webcodegeeks.com\/author\/federico-tomassetti\/"}]}},"_links":{"self":[{"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/posts\/17974","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/users\/149"}],"replies":[{"embeddable":true,"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/comments?post=17974"}],"version-history":[{"count":0,"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/posts\/17974\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/media\/920"}],"wp:attachment":[{"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/media?parent=17974"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/categories?post=17974"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/tags?post=17974"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}