How to write a parser in javascript to parse text

2019-06-08 16:56发布

问题:

I don't know if it is the place to ask this. But I will try.

What I need is, for example, if user writes some text in Code Mirror editor like:

a1=Some Text
    a11 = Some Child text

and the parser should check if the grammer is correct, and parse it to:

 {
    'a1' : {
             'value' : "Some Text",
             'a11' : "some child text"
    }
 }

Something like this according to the gramme.

So, is there any parser library or something in javascript?

回答1:

You should be able to use PEG.js to parse the text on the client side. I would also recommend to start off from writing a proper grammar for whatever valid input you are expecting from the user.



回答2:

This is a bit older, but will give an answer based on a codemirror grammar add-on i have written (as a result of some projects which required syntax-highlight for various custom languages).

One defines a grammar in JSON format for any language (or variation since json grammars can extend other json grammars) and the add-on creates automaticaly a codemirror parser which can include syntax parts and syntax-errors, autocompletion and more

See live example here