Skip to content

Commit

Permalink
Merge pull request #3 from base-cms/less-aggressive-space-stripping
Browse files Browse the repository at this point in the history
Do not strip single spaces inside elements
  • Loading branch information
zarathustra323 authored May 20, 2019
2 parents 661df22 + 5cae153 commit 61074fa
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 24 deletions.
27 changes: 5 additions & 22 deletions src/utils/strip-whitespace.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,11 @@
const cheerio = require('cheerio');

const cleanElementText = ($, $el) => {
const contents = $el.contents()[0];

if (contents && contents.type === 'text') {
const { data = '' } = contents;
const cleaned = data.replace(/\s\s+/g, ' ').trim();
contents.data = cleaned;
}
if ($el.children().length) {
$el.children().each(function () {
cleanElementText($, $(this));
});
}
};

module.exports = (html) => {
const str = (html || '')
.replace(/[\r\n\f\v\t\b\\]/g, ' ')
.replace(/[\r\n\f\v\t\b\\]/g, ' ')
.replace(/ /g, ' ')
.trim()
.replace(/>\s+</g, '><')
.replace(/\s+%{\[/g, '%{[')
.replace(/\]}%\s+/g, ']}%');
const $ = cheerio.load(str, { decodeEntities: false });
cleanElementText($, $('body'));
return $('body').html();
.replace(/\]}%\s+/g, ']}%')
.replace(/\s\s+/g, ' ');
return str;
};
2 changes: 1 addition & 1 deletion test/rules/pennwell/default.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ describe('rules/pennwell/default', () => {
<p>Hello, World</p>\t
`;
const result = await rule(body);
expect(result.html.cleaned).to.equal('<div><span>Bar</span><span>Foo Bar</span><span>Baz Bar</span></div><p>Hello, World</p>');
expect(result.html.cleaned).to.equal('<div><span>Bar </span><span>Foo Bar</span><span>Baz Bar</span></div><p>Hello, World</p>');
});
it('should remove <form> elements.', async () => {
const body = `
Expand Down
2 changes: 1 addition & 1 deletion test/utils/strip-whitespace.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ describe('utils/strip-whitespace', () => {
<p>Hello, World</p>\t
`;
const result = stripWhitespace(body);
expect(result).to.equal('<div><span>Bar</span><span>Foo<span>Bar Foo</span></span><span>Baz Bar</span></div><p>Hello, World</p>');
expect(result).to.equal('<div><span>Bar </span><span>Foo <span> Bar Foo</span></span><span>Baz Bar</span></div><p>Hello, World</p>');
});
it('should return an empty string for null values.', async () => {
expect(stripWhitespace()).to.equal('');
Expand Down

0 comments on commit 61074fa

Please sign in to comment.