JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.js"></script>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
Babel + JSX
const voidElementLookup = { area: true, base: true, br: true, col: true, embed: true, hr: true, img: true, input: true, keygen: true, link: true, menuitem: true, meta: true, param: true, source: true, track: true, wbr: true,
}
function parseTag(html) {
// const name/label = /([\w-]+)/;
// const assignment = /=/;
// const wrappingQuote = /['"]/;
// const nonWrappingQuote = /([^'"]*)/
//This will match any =NameSpace or ="value" or nothing at all
const matches = html.match(/([\w-]+)(=(([\w-]+)|(['"]([^'"]*)['"])))?/g);
const name = matches.shift();
let elm = {
type: 'tag',
name,
voidElement: (voidElementLookup[name] || html[html.length - 2] === '/'),
attr: {},
standaloneAttr: {}
}
for (const str of matches) {
const [ key, value ] = str.split(/=(.+)/);
if (!value) {
elm.standaloneAttr[key] = true
} else {
elm.attr[key] = value.replace(/(^['"])(.*)(['"]$)/, '$2') // remove extra "/' created by split.
}
}
return elm;
}
let tag = `<form id="testForm" class="ui form three column p3-form" autocomplete="off" novalidate="" required>`
console.log(parseTag(tag))
tag = '<div class=thing other=stuff something=54 quote="me ">';
console.log(parseTag(tag))
tag = '<something-custom class=\'single quoted thing\'>';
console.log(parseTag(tag))
tag = '</p>';
console.log(parseTag(tag))
tag = '<img src="something" alt="sweet picture"/>';
console.log(parseTag(tag))