Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomhodgins/eeb921d01cbc1a1dbf412d3b0ac2ff92 to your computer and use it in GitHub Desktop.
Save tomhodgins/eeb921d01cbc1a1dbf412d3b0ac2ff92 to your computer and use it in GitHub Desktop.
function processSelfClosingTags(string = '') {
const dom = document.implementation.createHTMLDocument().createRange().createContextualFragment(string)
function consumeNode(node = document.createElement('span')) {
if (
node.nodeType === 8
&& node.textContent.match(/^\?.+\?$/)
) {
node.replaceWith(
document.createElement(
node.textContent.replace(/\?/g, '').trim()
)
)
}
// Process children
if (node.childNodes.length) {
node.childNodes.forEach(consumeNode)
}
return node
}
return consumeNode(dom)
}
let result = processSelfClosingTags(`Well <b>hello <?self-close?> there`)
// Well <b>hello <self-close></self-close> there!</b>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment