There is some string (for example, 's'):
import 'lodash';
// TODO import jquery
//import 'jquery';
/*
Some very important comment
*/
How can I remove all comments from 's' string? Should I use some Regexp for it? I don't know.
The replace() method is one of the most commonly used techniques to remove the character from a string in javascript. The replace() method takes two parameters, the first of which is the character to be replaced and the second of which is the character to replace it with.
Complete HTML/CSS Course 2022 Comments are used to hide content. To create hidden comments in HTML, we add <! --- tag and end it with -- >. Whatever comes inside this tag it is hidden.
Multi-line or block comments serve the same purpose and as the name suggest, it expands into multiple lines. Usually, most developers use /* and */ syntax to write multi-line block comments. But the standard way to use block comments in JavaScript is to; Start with /** in a blank line. End with */ at the end line.
The one from @MarcoS won't work in several cases...
Below is my solution:
str.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g,'');
Removing comments from a string:
function removeComments(string){
//Takes a string of code, not an actual function.
return string.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g,'').trim();//Strip comments
}
const commentedcode = `
alert('hello, this code has comments!')//An alert
/* A block comment here */
// A single line comment on a newline
`;
console.log(removeComments(commentedcode));
Using RegExr.com:
console.log(`
var myStr = 'я! This \\'seems\\' to be a // comment'; // but this is actually the real comment.
/* like this one */ var butNot = 'this "/*one*/"'; // but this one and /* this one */
/* and */ var notThis = "one '//but' \\"also\\""; /* // this one */
`
// 1) replace "/" in quotes with non-printable ASCII '\1' char
.replace(/("([^\\"]|\\")*")|('([^\\']|\\')*')/g, (m) => m.replace(/\//g, '\1'))
// 2) clear comments
.replace(/(\/\*[^*]+\*\/)|(\/\/[^\n]+)/g, '')
// 3) restore "/" in quotes
.replace(/\1/g, '/')
);
If you want to use a RegExp, you could use this one:
/(\/\*[^*]*\*\/)|(\/\/[^*]*)/
This should strip both // ... \n
style comments and /* ... */
style comments.
var stringWithoutComments = s.replace(/(\/\*[^*]*\*\/)|(\/\/[^*]*)/g, '');
console.log(stringWithoutComments);
var s = `before
/* first line of comment
second line of comment */
after`;
var stringWithoutComments = s.replace(/(\/\*[^*]*\*\/)|(\/\/[^*]*)/g, '');
console.log(stringWithoutComments);
outputs:
before
after
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With