Created
June 4, 2022 12:51
-
-
Save worldoptimizer/f7ebab78f1a65f8211913b9c8fdddf43 to your computer and use it in GitHub Desktop.
Extract the comments from a string.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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