-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix(core): fix new lines being added via elementFromString (#4767)
Co-authored-by: bdbch <dominik@bdbch.com>
- Loading branch information
Showing
3 changed files
with
28 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,26 @@ | ||
const removeWhitespaces = (node: HTMLElement) => { | ||
const children = node.childNodes | ||
|
||
for (let i = children.length - 1; i >= 0; i -= 1) { | ||
const child = children[i] | ||
|
||
if (child.nodeType === 3 && child.nodeValue && !/\S/.test(child.nodeValue)) { | ||
node.removeChild(child) | ||
} else if (child.nodeType === 1) { | ||
removeWhitespaces(child as HTMLElement) | ||
} | ||
} | ||
|
||
return node | ||
} | ||
|
||
export function elementFromString(value: string): HTMLElement { | ||
// add a wrapper to preserve leading and trailing whitespace | ||
const wrappedValue = `<body>${value}</body>` | ||
|
||
return new window.DOMParser().parseFromString(wrappedValue, 'text/html').body | ||
const html = new window.DOMParser().parseFromString(wrappedValue, 'text/html').body | ||
|
||
removeWhitespaces(html) | ||
|
||
return removeWhitespaces(html) | ||
} |