(1)安装pegjs
bower install pegjs
(2)index.html
<script src="bower_components/pegjs/peg-0.8.0.min.js"></script>
(3)页面中使用
var parser=window.PEG.buildParser('\
start\n\
= additive\n\
\n\
additive\n\
= left:multiplicative "+" right:additive { return left + right; }\n\
/ multiplicative\n\
\n\
multiplicative\n\
= left:primary "*" right:multiplicative { return left * right; }\n\
/ primary\n\
\n\
primary\n\
= integer\n\
/ "(" additive:additive ")" { return additive; }\n\
\n\
integer "integer"\n\
= digits:[0-9]+ { return parseInt(digits.join(""), 10); }\n\
');
var result=parser.parse('1+2*3');
console.log(result);