var extract = require('extract-comments');
// pass a string of JavaScript
extract(string);
Example
var str = '/**\n * this is\n *\n * a comment\n*/\n\n\nvar foo = "bar";\n';
var comments = extract(str);
console.log(comments);
[{
type: 'block',
raw: '/**\n * this is\n *\n * a comment\n*/',
value: 'this is\na comment',
loc: { start: { line: 1, column: 0 }, end: { line: 5, column: 33 } },
code:
{ line: 7,
loc: { start: { line: 7, column: 36 }, end: { line: 7, column: 52 } },
value: 'var foo = "bar";' }
By default, [esprima][] is used for extracting comments. This can easily be changed by passing a function to options.extractor
.
The easy way
Use a published module, such as:
- [babel-extract-comments][]
- [esprima-extract-comments][]
- [espree-extract-comments][]
Example:
extract(str, {extractor: require('babel-extract-comments')});
If you create a compatible extractor, feel free to do pr or create an issue to add it to the readme!
Roll your own
extract(str, {
extractor: function(str) {
// must return an array of tokens with:
// - type: 'Block', 'CommentBlock', 'Line' or 'CommentLine'
// - value: the comment inner string
// - loc: with `start` and `end` line and column
// example:
return [
{
type: 'Block',
{start: { line: 1, column: 0 },
end: { line: 5, column: 33 }},
value: ' this is a comment string '
}
];
}
});
{%= apidocs("index.js") %}
v0.10.0
- Parsing is now handled by esprima, so only JavaScript can be parsed. I'm working on parsers for other languages and will cross-link those here when they're pushed up.
- Breaking change: since parsing is now done by esprima, on both the line and block comment objects, the
loc.start.pos
andloc.end.pos
properties have been renamed toloc.start.column
andloc.end.column
.
v0.9.0
- Breaking change:
lines
property was removed fromBlock
comments, since this can easily be done by splittingvalue