Skip to content

Instantly share code, notes, and snippets.

@DavidWells
Created February 24, 2022 04:23
Show Gist options
  • Save DavidWells/52a52efe7816fda9ce82e4a3e293941a to your computer and use it in GitHub Desktop.
Save DavidWells/52a52efe7816fda9ce82e4a3e293941a to your computer and use it in GitHub Desktop.
Trim comments from a string
// via https://github.com/suchipi/without-comments/blob/main/index.js
function trimComments(content, commentToken = "#") {
const startRegex = new RegExp(`^${commentToken}`);
const endRegex = new RegExp(`${commentToken}.*$`, "g");
return content
.split("\n")
.map((line) => {
// remove comment lines
if (startRegex.test(line.trim())) return "";
// remove trailing comments
line = line.replace(endRegex, "");
return line;
})
.filter((line) => line != null)
.join("\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment