From 58a8f8c4147782f6d8719abb00cfd91323688ec1 Mon Sep 17 00:00:00 2001 From: Mimi <1119186082@qq.com> Date: Fri, 25 Nov 2022 20:27:08 +0800 Subject: [PATCH] feat(tags/img): support quotes in img title and alt (#5112) --- lib/plugins/tag/img.js | 8 ++++++-- test/scripts/tags/img.js | 22 ++++++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/lib/plugins/tag/img.js b/lib/plugins/tag/img.js index 5b913beeda..0a1ef7073e 100644 --- a/lib/plugins/tag/img.js +++ b/lib/plugins/tag/img.js @@ -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 @@ -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) { diff --git a/test/scripts/tags/img.js b/test/scripts/tags/img.js index 30a8cfa53a..7030c92a41 100644 --- a/test/scripts/tags/img.js +++ b/test/scripts/tags/img.js @@ -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'); + }); });