I would like to remove all single comments // and block comments /* */ of a line inside a string.
However, if those comments are inside the characters '', "", [] and/or `` it should not be removed.
Examples:
='a' &
'//b/*aasdsa //dsfds*/'& //comment
'//d' /*aasdsa //dsfds*/ & '//e' & /*aasdsa //dsfds*/
& 'c'
[// /* [] */] & h
`// /* [] */` & p
Should be:
='a' &
'//b'&
'//d' & '//e' &
& 'c'
& h
& p
I have tried different solutions but I haven't got too far.
let text = "='a' &
'//b'& //comment expression
'//d' /*aasdsa //dsfds*/ & '//e' & /*aasdsa //dsfds*/
& 'c'";
let arrayText = text.split('\n');
arrayText = arrayText.filter(a => a.indexOf('//') !== 0);
arrayContent = arrayContent.map(x =>
x.replace(/[^\(?<=\').*(?=\'$)|\(?<=\[).*(?=\]$](\/\*[\s\S]*?\*\/|\/\/.*)/gm, ''));
text = arrayContent.join(' ');
With the solution that I tried I just got the following:
Text:
='a' &
'//b/*aasdsa //dsfds*/'& //comment
'//d' /*aasdsa //dsfds*/ & '//e' & /*aasdsa //dsfds*/
& 'c'
[// /* [] */] & h
`// /* [] */` & p
Result with my solution (that doesn't work)
='a' &
'//b'&
'//d' & '//e' &
& 'c'
[//]
Expected result:
='a' &
'//b/*aasdsa //dsfds*/'&
'//d' & '//e' &
& 'c'
[// /* [] */] & h
`// /* [] */` & p
I would appreciate if somebody can point me what I am missing or any other hint.
'//b'string that gets removed. Is that intentional?