Skip to content

Instantly share code, notes, and snippets.

@numbcoder
Created October 18, 2012 09:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save numbcoder/3910568 to your computer and use it in GitHub Desktop.
Save numbcoder/3910568 to your computer and use it in GitHub Desktop.
remove js or json comments
/**
* Removes JavaScript comments from a string by replacing
* everything between block comments and everything after
* single-line comments in a non-greedy way.
*
* English version of the regex:
* match '/*'
* then match zero or more instances of any character (incl. \n)
* except for instances of '* /' (without a space, obv.)
* then match '* /' (again, without a space)
*
* @param {string} str a string with potential JavaScript comments.
* @returns {string} a string without JavaScript comments.
*/
function removeComments(str) {
str = str || "";
str = str.replace(/\/\*(?:(?!\*\/)[\s\S])*\*\//g, "");
// Everything after '//'
str = str.replace(/\/\/[^\n\r]*/g, "");
return str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment