Skip to content

Commit

Permalink
Merge pull request #4 from timmkrause/master
Browse files Browse the repository at this point in the history
Support image size in image links
  • Loading branch information
tcort authored May 30, 2018
2 parents 47411cc + 4f30c38 commit 22a7f8d
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
12 changes: 10 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,21 @@ module.exports = function markdownLinkExtractor(markdown) {
var links = [];

var renderer = new marked.Renderer();

// Taken from https://github.com/markedjs/marked/issues/1279
var linkWithImageSizeSupport = /^!?\[((?:\[[^\[\]]*\]|\\[\[\]]?|`[^`]*`|[^\[\]\\])*?)\]\(\s*(<(?:\\[<>]?|[^\s<>\\])*>|(?:\\[()]?|\([^\s\x00-\x1f()\\]*\)|[^\s\x00-\x1f()\\])*?(?:\s+=(?:[\w%]+)?x(?:[\w%]+)?)?)(?:\s+("(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)))?\s*\)/;

marked.InlineLexer.rules.normal.link = linkWithImageSizeSupport;
marked.InlineLexer.rules.gfm.link = linkWithImageSizeSupport;
marked.InlineLexer.rules.breaks.link = linkWithImageSizeSupport;

renderer.link = function (href, title, text) {
links.push(href);
return marked.Renderer.prototype.link.apply(this, arguments);
};
renderer.image = function (href, title, text) {
// Remove image size at the end, e.g. ' =20%x50'
href = href.replace(/ =\d*%?x\d*%?$/, "");
links.push(href);
return marked.Renderer.prototype.image.apply(this, arguments);
};
marked(markdown, { renderer: renderer });

Expand Down
14 changes: 14 additions & 0 deletions test/markdown-link-extractor.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,20 @@ describe('markdown-link-extractor', function () {
expect(links[0]).to.be('http://www.example.com/image.jpg');
});

it('should extract an image link in a ![tag](foo/image.jpg)', function () {
var links = markdownLinkExtractor('![example](foo/image.jpg)');
expect(links).to.be.an('array');
expect(links).to.have.length(1);
expect(links[0]).to.be('foo/image.jpg');
});

it('should extract an image link in a ![tag](foo/image.jpg =20%x50)', function () {
var links = markdownLinkExtractor('![example](foo/image.jpg =20%x50)');
expect(links).to.be.an('array');
expect(links).to.have.length(1);
expect(links[0]).to.be('foo/image.jpg');
});

it('should extract a bare link http://example.com', function () {
var links = markdownLinkExtractor('This is a link: http://www.example.com');
expect(links).to.be.an('array');
Expand Down

0 comments on commit 22a7f8d

Please sign in to comment.