Reputation:
I´m writing a program to scan code files and have to remove comments first. Single- and Multiline comments.
The single line comments seem to work out perfectly but somehow the multiline part doesn´t seem to work properly.
It does find the multiline comment but doesn´t replace it. when using
outputCode.replace(multilineComment, '');
my function:
// remove all comments by removing everything between the matches indexes and the next endOfCommentRegex
const removeAllComments = async (endOfCommentRegex: RegExp, matches: RegExpMatchArray[]) => {
let comments: string[] = [];
matches.forEach(async match => {
// find the next endOfCommentRegex after the match.index
const endOfCommentMatch = outputCode.slice(match.index).match(endOfCommentRegex);
if (endOfCommentMatch) {
// store everything between the match.index and the endOfCommentMatch.index in a variable if the char at match.index - 1 is not a : (for https://...)
if (outputCode.charAt(match.index! - 1) !== ':') {
comments.push(outputCode.slice(match.index, match.index! + endOfCommentMatch.index! + 2));
}
}
});
// remove all comments from the outputCode
comments.forEach(comment => {
outputCode = outputCode.replace(comment, '');
});
};
and call the function like so:
// check for all multiline comments
const multiMatches = [...outputCode.matchAll(/\/\*/g)];
if (multiMatches.length !== 0) {
await removeAllComments(/\*\//, multiMatches);
}
expected output: the file(string)content without the multiline in it.
current output: file(string)content + multilineComment + file(string)content
I have no idea, why it cocatinates the string that weird instead of simply replacing the comment.
Any idea what could be wrong here?
edit: like I said, it does find the multiline comment and safes it in the comments array like so: "/* multiline dummy comment */"
Upvotes: 0
Views: 261
Reputation: 137
This regex works for me /(\/\*(.*?\n*)*?\*\/)/g
let reg = /(\/\*(.*?\n*)*?\*\/)/g;
outputCode = outputCode.replace(reg, '');
Upvotes: 1