Skip to content

Instantly share code, notes, and snippets.

@chuchuva
Created May 3, 2023 01:49
Show Gist options
  • Save chuchuva/a5be703e22a4caf16073404f3b02adcb to your computer and use it in GitHub Desktop.
Save chuchuva/a5be703e22a4caf16073404f3b02adcb to your computer and use it in GitHub Desktop.
How to format XML string in JavaScript
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