Created
May 3, 2023 01:49
-
-
Save chuchuva/a5be703e22a4caf16073404f3b02adcb to your computer and use it in GitHub Desktop.
How to format XML string in JavaScript
This file contains hidden or 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 formatXML(xml, tab = ' ', nl = '\n') { | |
let formatted = '', indent = ''; | |
const nodes = xml.slice(1, -1).split(/>\s*</); | |
if (nodes[0][0] == '?') formatted += '<' + nodes.shift() + '>' + nl; | |
for (let i = 0; i < nodes.length; i++) { | |
const node = nodes[i]; | |
if (node[0] == '/') indent = indent.slice(tab.length); // decrease indent | |
formatted += indent + '<' + node + '>' + nl; | |
if (node[0] != '/' && node[node.length - 1] != '/' && node.indexOf('</') == -1) indent += tab; // increase indent | |
} | |
return formatted; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment