Created
April 3, 2024 23:54
-
-
Save tomhodgins/eeb921d01cbc1a1dbf412d3b0ac2ff92 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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