Skip to content

Commit

Permalink
feat(tags/img): support quotes in img title and alt (#5112)
Browse files Browse the repository at this point in the history
  • Loading branch information
stevenjoezhang authored Nov 25, 2022
1 parent 0a43fd5 commit 58a8f8c
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
8 changes: 6 additions & 2 deletions lib/plugins/tag/img.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
const { htmlTag, url_for } = require('hexo-util');

const rUrl = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=+$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=+$,\w]+@)[A-Za-z0-9.-]+)((?:\/[+~%/.\w-_]*)?\??(?:[-+=&;%@.\w_]*)#?(?:[.!/\\w]*))?)/;
const rMeta = /["']?([^"']+)?["']?\s*["']?([^"']+)?["']?/;
const rMetaDoubleQuote = /"?([^"]+)?"?/;
const rMetaSingleQuote = /'?([^']+)?'?/;

/**
* Image tag
Expand Down Expand Up @@ -38,7 +39,10 @@ module.exports = ctx => {
}
}

const match = rMeta.exec(args.join(' '));
const meta = args.join(' ');
const rMetaTitle = meta.startsWith('"') ? rMetaDoubleQuote : rMetaSingleQuote;
const rMetaAlt = meta.endsWith('"') ? rMetaDoubleQuote : rMetaSingleQuote;
const match = new RegExp(`${rMetaTitle.source}\\s*${rMetaAlt.source}`).exec(meta);

// Find image title and alt
if (match != null) {
Expand Down
22 changes: 22 additions & 0 deletions test/scripts/tags/img.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,4 +127,26 @@ describe('img', () => {
$('img').attr('title').should.eql('Place Kitten');
$('img').attr('alt').should.eql('A cute kitten');
});

it('single quote in double quote', () => {
const $ = cheerio.load(img('left https://placekitten.com/200/300 200 300 "Place Kitten" "A \'cute\' kitten"'.split(' ')));

$('img').attr('src').should.eql('https://placekitten.com/200/300');
$('img').attr('class').should.eql('left');
$('img').attr('width').should.eql('200');
$('img').attr('height').should.eql('300');
$('img').attr('title').should.eql('Place Kitten');
$('img').attr('alt').should.eql('A \'cute\' kitten');
});

it('double quote in single quote', () => {
const $ = cheerio.load(img('left https://placekitten.com/200/300 200 300 "Place Kitten" \'A "cute" kitten\''.split(' ')));

$('img').attr('src').should.eql('https://placekitten.com/200/300');
$('img').attr('class').should.eql('left');
$('img').attr('width').should.eql('200');
$('img').attr('height').should.eql('300');
$('img').attr('title').should.eql('Place Kitten');
$('img').attr('alt').should.eql('A "cute" kitten');
});
});

0 comments on commit 58a8f8c

Please sign in to comment.