Skip to content
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
7 changes: 5 additions & 2 deletions lib/html_tag.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
const encodeURL = require('./encode_url');
const escapeHTML = require('./escape_html');
const regexUrl = /(cite|download|href|src|url)$/i;
const regexMeta = /^(og:|twitter:)(audio|image|url|video)(:secure_url)?$/i;

function encSrcset(str) {
str.split(' ')
Expand All @@ -23,8 +24,10 @@ function htmlTag(tag, attrs, text, escape = true) {
for (const i in attrs) {
if (attrs[i] === null || typeof attrs[i] === 'undefined') result += '';
else {
if (i.match(regexUrl)) result += ` ${escapeHTML(i)}="${encodeURL(attrs[i])}"`;
else if (attrs[i] === true || i === attrs[i]) result += ` ${escapeHTML(i)}`;
if (i.match(regexUrl)
|| (tag === 'meta' && !attrs[i].match(regexMeta) && Object.values(attrs)[0].match(regexMeta))) {
result += ` ${escapeHTML(i)}="${encodeURL(attrs[i])}"`;
} else if (attrs[i] === true || i === attrs[i]) result += ` ${escapeHTML(i)}`;
else if (i.match(/srcset$/i)) result += ` ${escapeHTML(i)}="${encSrcset(attrs[i])}"`;
else result += ` ${escapeHTML(i)}="${escapeHTML(String(attrs[i]))}"`;
}
Expand Down
38 changes: 38 additions & 0 deletions test/html_tag.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ require('chai').should();

describe('htmlTag', () => {
const htmlTag = require('../lib/html_tag');
const encodeURL = require('../lib/encode_url');

it('tag', () => {
htmlTag('hr').should.eql('<hr>');
Expand Down Expand Up @@ -113,4 +114,41 @@ describe('htmlTag', () => {
async: true
}, '').should.eql('<script src="/foo.js" async></script>');
});

it('meta tag', () => {
htmlTag('meta', {
property: 'og:title',
content: 'foo & bar'
}).should.eql('<meta property="og:title" content="foo &amp; bar">');

htmlTag('meta', {
name: 'twitter:title',
content: 'foo " bar'
}).should.eql('<meta name="twitter:title" content="foo &quot; bar">');
});

it('meta tag - url', () => {
const content = 'https://foo.com/bár.jpg';
const encoded = encodeURL(content);

htmlTag('meta', {
property: 'og:url',
content
}).should.eql(`<meta property="og:url" content="${encoded}">`);

htmlTag('meta', {
property: 'og:image:secure_url',
content
}).should.eql(`<meta property="og:image:secure_url" content="${encoded}">`);

htmlTag('meta', {
name: 'twitter:image',
content
}).should.eql(`<meta name="twitter:image" content="${encoded}">`);

htmlTag('meta', {
name: 'foo image',
content: 'bar " baz'
}).should.eql('<meta name="foo image" content="bar &quot; baz">');
});
});