Skip to content

Commit 5b493b8

Browse files
committed
Trim whitespace-only text nodes from the start and end of HTML strings since they're not inside a tag.
1 parent 99d99ec commit 5b493b8

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

lib/parse.js

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ var parseTag = require('./parse-tag');
44
// re-used obj for quick lookups of components
55
var empty = Object.create ? Object.create(null) : {};
66
// common logic for pushing a child node onto a list
7-
function pushTextNode(list, html, start, ignoreWhitespace) {
7+
function pushTextNode(list, html, level, start, ignoreWhitespace) {
88
// calculate correct end of the content slice in case there's
99
// no tag after the text node.
1010
var end = html.indexOf('<', start);
@@ -14,7 +14,11 @@ function pushTextNode(list, html, start, ignoreWhitespace) {
1414
if (/^\s*$/.test(content)) {
1515
content = ' ';
1616
}
17-
if (!ignoreWhitespace || content !== ' ') {
17+
// don't add whitespace-only text nodes if they would be trailing text nodes
18+
// or if they would be leading whitespace-only text nodes:
19+
// * end > -1 indicates this is not a trailing text node
20+
// * leading node is when level is -1 and list has length 0
21+
if ((!ignoreWhitespace && end > -1 && level + list.length >= 0) || content !== ' ') {
1822
list.push({
1923
type: 'text',
2024
content: content
@@ -57,7 +61,7 @@ module.exports = function parse(html, options) {
5761
}
5862

5963
if (!current.voidElement && !inComponent && nextChar && nextChar !== '<') {
60-
pushTextNode(current.children, html, start, options.ignoreWhitespace);
64+
pushTextNode(current.children, html, level, start, options.ignoreWhitespace);
6165
}
6266

6367
byTag[current.tagName] = current;
@@ -85,14 +89,14 @@ module.exports = function parse(html, options) {
8589
// if we're at the root, push a base text node. otherwise add as
8690
// a child to the current node.
8791
parent = level === -1 ? result : arr[level].children;
88-
pushTextNode(parent, html, start, options.ignoreWhitespace);
92+
pushTextNode(parent, html, level, start, options.ignoreWhitespace);
8993
}
9094
}
9195
});
9296

9397
// If the "html" passed isn't actually html, add it as a text node.
9498
if (!result.length && html.length) {
95-
pushTextNode(result, html, 0, options.ignoreWhitespace);
99+
pushTextNode(result, html, 0, 0, options.ignoreWhitespace);
96100
}
97101

98102
return result;

0 commit comments

Comments
 (0)