HTML parser

Turn HTML string into object

by Danny Michaelis

Babel + JSX

const elmOpen 			= /^\s*(<)/;
const elmType 			= /^\s*(\w+)/;
const closeTag			= /^\s*(>)/;
const closeElm 			= /^\s*\/(\w*)>/ ;
const attrKey 			= /^\s*([\w-]+)/;
const partialAttrKey 	= /^\s{0}([\w-]+)/;
const assignment		= /^\s*(=)/;
const openAssignment	= /^\s*(["'])/;
const attrValue 		= /^\s*([^"']+)["']/; // /^\s*(.+)["']{1}/;
const closedAssignment 	= /^\s*.{0}(["'])/;
const standAloneText 	= /^\s*([^<>/]+)/;
const unquotedValue 	= /^([^\s"'`=<>]+)\s+/;

const parseTree = {
    'start': 			{ elmOpen, standAloneText, closeElm }, // Always first
    'elmOpen': 			{ closeTag, closeElm, elmType }, // Always Second
    'elmType': 			{ closeTag, closeElm, attrKey }, // Always Third
    'attrKey': 			{ closeTag, closeElm, partialAttrKey, attrKey, assignment }, // Loop
    'partialAttrKey': 	{ closeTag, closeElm, partialAttrKey, attrKey, assignment }, // Loop
    'assignment':		{ openAssignment, closedAssignment, unquotedValue },
    'openAssignment': 	{ closedAssignment, attrValue },
    'unquotedValue':	{ closeTag, closeElm, attrKey },
    'attrValue': 		{ closeTag, closeElm, attrKey }, // attrValue searches for a closing quote, consumes it & loops back to gatherAttributes
    'closedAssignment':	{ closeTag, closeElm, attrKey }, // closedAssignment loops back to gatherAttributes
    'closeElm':			{ elmOpen, standAloneText, closeElm },
    'standAloneText':	{ elmOpen, standAloneText, closeElm },
    'closeTag':			{ elmOpen, standAloneText, closeElm }
};

class Parser {
    constructor(parseTree) {
        this.parseState = 'start';
        this.parseTree = parseTree;
        this.previousMatch = {
            ruleName: '',
            capturedString: ''
        };
        this.ctr = 0;
    }

    setRuleState(stateString) {
        this.parseState = stateString;
        return this;
    }

    getRuleSet() {
        return this.parseTree[this.parseState];
    }

    parse(str) {
        return () => {
            let ctr = 0;
            let elementObject = {
  ...