Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(tags/img): support quotes in img title and alt #5112

Merged
merged 1 commit into from
Nov 25, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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');
});
});