Skip to content

Instantly share code, notes, and snippets.

@worldoptimizer
Created June 4, 2022 12:51
Show Gist options
  • Save worldoptimizer/f7ebab78f1a65f8211913b9c8fdddf43 to your computer and use it in GitHub Desktop.
Save worldoptimizer/f7ebab78f1a65f8211913b9c8fdddf43 to your computer and use it in GitHub Desktop.
Extract the comments from a string.
/**
* Extract the comments from a string.
* @param {string} str - The string to extract the comments from.
* @returns {Array.<string>} - An array of comment strings.
*/
function getCommentsFromString(str) {
str = str.toString();
var start = str.indexOf("/*");
var end = str.indexOf("*/");
var result = [];
while (start !== -1) {
result.push(str.slice(start + 2, end));
start = str.indexOf("/*", end + 2);
end = str.indexOf("*/", end + 2);
}
return result;
}
/* the same as a parser approach */
function getCommentsFromString(str) {
var start = str.indexOf("/*"),
end = str.indexOf("*/"),
i = 0,
len = str.length,
comment = "",
char = "";
var result = [];
while (i < len) {
char = str[i];
if (char === "/" && str[i + 1] === "*") {
start = i;
i += 2;
while (i < len) {
char = str[i];
if (char === "*" && str[i + 1] === "/") {
end = i;
i += 2;
break;
}
comment += char;
i++;
}
result.push(comment);
comment = "";
}
i++;
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment