Stripping comments from XML shouldn't be hard.
But one wrong regex and you accidentally delete code instead of comments. You break the markup. You corrupt the file.
Let's look at why regex fails and how to strip comments safely.
What XML Comments Look Like
XML comments start with <!-- and end with -->. They can be a single line or span multiple lines.
<!-- This is a single-line comment -->
<user>
<name>Alice</name>
<!--
This is a multi-line comment.
It can contain anything.
-->
<role>Admin</role>
</user>
Comments are useful for developers but often need to be stripped before deployment to save space or hide internal notes.
The Dangerous Way (Regex)
Most developers try to solve this with a regular expression:
const stripped = xml.replace(/<!--[\s\S]*?-->/g, '');
This works 99% of the time. But XML is not a regular language, and regex is easily broken by edge cases.
What happens if a comment contains the string --> inside a string literal? What if it's nested inside a CDATA section?
<![CDATA[
<!-- This is NOT a comment, it's data! -->
]]>
If you run the regex on this, it will delete the data inside the CDATA section, corrupting your file.
The Safe Way (DOM Parsing)
The only safe way to remove comments is to parse the XML into a DOM (Document Object Model), find the comment nodes, and remove them.
This handles CDATA sections, attributes, and nested comments correctly because the parser understands the structure.
function stripComments(xmlString) {
const parser = new DOMParser();
const doc = parser.parseFromString(xmlString, "application/xml");
// Check for parsing errors
const parseError = doc.querySelector("parsererror");
if (parseError) throw new Error("Invalid XML");
// Recursively remove comment nodes
function removeComments(node) {
// Iterate backwards to safely remove nodes while looping
for (let i = node.childNodes.length - 1; i >= 0; i--) {
const child = node.childNodes[i];
if (child.nodeType === Node.COMMENT_NODE) {
node.removeChild(child);
} else if (child.nodeType === Node.ELEMENT_NODE) {
removeComments(child);
}
}
}
removeComments(doc);
const serializer = new XMLSerializer();
return serializer.serializeToString(doc);
}
This requires a few lines of code and a DOM parser, but it guarantees you won't accidentally delete actual data.
The Visual Way
If you just need to strip comments quickly without writing a script, I built a free XML Comments Stripper.
What it does:
- Safely removes single-line and multi-line XML comments
- Preserves document integrity
- Won't break your markup
Why it's useful:
- No installation
- No upload (100% client-side)
- Handles edge cases
Try It
100% client-side. Nothing uploaded.
Have you ever broken an XML file with a bad regex? Let me know in the comments.
Top comments (0)