Security News
ESLint is Now Language-Agnostic: Linting JSON, Markdown, and Beyond
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
html-parse-stringify
Advanced tools
Parses well-formed HTML (meaning all tags closed) into an AST and back. quickly.
The html-parse-stringify npm package is a lightweight tool for parsing HTML into AST (Abstract Syntax Tree) and vice versa, i.e., stringifying AST back into HTML. It is particularly useful for tasks where you need to manipulate or analyze HTML structures programmatically without the overhead of a full DOM parser.
Parsing HTML to AST
This feature allows you to convert an HTML string into a structured AST, which can be easily manipulated or analyzed in JavaScript.
const htmlParseStringify = require('html-parse-stringify');
const ast = htmlParseStringify.parse('<div>Hello, <strong>world!</strong></div>');
Stringifying AST to HTML
This feature enables you to take an AST and convert it back into an HTML string. This is useful when you have manipulated the AST and want to generate the updated HTML.
const htmlParseStringify = require('html-parse-stringify');
const ast = [{ tag: 'div', attrs: {}, children: [{ text: 'Hello, ' }, { tag: 'strong', attrs: {}, children: [{ text: 'world!' }] }] }];
const html = htmlParseStringify.stringify(ast);
Parse5 is a full-fledged HTML parsing/serialization toolset for Node.js, which adheres to the HTML5 specification. It is more feature-rich and heavier compared to html-parse-stringify, providing a full DOM tree rather than a simple AST.
Cheerio is a fast, flexible, and lean implementation of core jQuery designed specifically for the server. It uses a subset of the parse5 parser and provides a familiar jQuery interface to manipulate the parsed HTML structure. It is more powerful for DOM manipulation but also heavier than html-parse-stringify.
Htmlparser2 is a forgiving HTML and XML parser. It is faster and less strict than parse5, making it a good alternative for parsing imperfect HTML. It provides a callback-based API for handling parsed data, which is different from the AST approach of html-parse-stringify.
This is an experimental lightweight approach to enable quickly parsing HTML into an AST and stringify'ing it back to the original string.
As it turns out, if you can make a the simplifying assumptions about HTML that all tags must be closed or self-closing. Which is OK for this particular application. You can write a super light/fast parser in JS with regex.
"Why on earth would you do this?! Haven't you read: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags ?!?!"
Why yes, yes I have :)
But the truth is. If you could do this in a whopping grand total of ~600 bytes (min+gzip) as this repo shows. It potentially enables DOM diffing based on a HTML strings to be super light and fast in a browser. What is that you say? DOM-diffing?
Yes.
React.js essentially pioneered the approach. With Reach you render to a "virtual DOM" whenever you want to, and the virtual DOM can then diff against the real DOM (or the last virtual DOM) and then turn that diff into whatever transformations are necessary to get the real DOM to match what you rendered as efficiently as possible.
As a result, when you're building a single page app, you don't have to worry so much about bindings. Instead, you simple re-render to the virtual DOM whenever you know something's changed. All of a sudden being able to have change
events for individual properties becomes less important, instead you can just reference those values in your template whenever you think something changed.
Cool idea, right?!
Well, there are other things React expects me to do if I use it that I don't like. Such as the custom templating and syntax you have to use.
If, hypothetically, you could instead diff an HTML string (generated by whatever templating language of your choice) against the DOM, then you'd get the same benefit, sans React's impositions.
This may all turn out to be a bad idea altogether, but initial results seem promising when paired with virtual-dom.
But you can't just diff HTML strings, as simple strings, very easily, in order to diff two HTML node trees you have to first turn that string into a tree structure of some sort. Typically, the thing you generate from parsing something like this is called an AST (abstract syntax tree).
This lib does exactly that.
It has two methods:
.parse(htmlString, options)
Takes a sting of HTML and turns it into an AST, the only option you can currently pass is an object of registered components
whose children will be ignored when generating the AST.
.stringify(AST)
Takes an AST and turns it back into a string of HTML.
See comments in the following example:
var HTML = require('html-parse-stringify')
// this html:
var html = '<div class="oh"><p>hi</p></div>';
// becomes this AST:
var ast = HTML.parse(html);
console.log(ast);
/*
{
// can be `tag`, `text` or `component`
type: 'tag',
// name of tag if relevant
name: 'div',
// parsed attribute object
attrs: {
class: 'oh'
},
// whether this is a self-closing tag
// such as <img/>
selfClosing: false,
// an array of child nodes
// we see the same structure
// repeated in each of these
children: [
{
type: 'tag',
name: 'p',
attrs: {},
selfClosing: false,
children: [
// this is a text node
// it also has a `type`
// but nothing other than
// a `content` containing
// its text.
{
type: 'text',
content: 'hi'
}
]
}
]
}
*/
properties:
type
- will always be tag
for this type of nodename
- tag name, such as 'div'attrs
- an object of key/value pairs. If an attribute has multiple space-separated items such as classes, they'll still be in a single string, for example: class: "class1 class2"
selfClosing
- true
or false
. Whether this tag has a self-closing slash such as: <img/>
, or <input/>
children
- array of child nodes. Note that any continuous string of text is a text node child, see below.properties:
type
- will always be text
for this type of nodecontent
- text content of the nodeIf you pass an object of components
as part of the options
object passed as the second argument to .parse()
then the AST won't keep parsing that branch of the DOM tree when it one of those registered components.
This is so that it's possible to ignore sections of the tree that you may want to handle by another "subview" in your application that handles it's own DOM diffing.
properties:
type
- will always be component
for this type of nodename
- tag name, such as 'div'attrs
- an object of key/value pairs. If an attribute has multiple space-separated items such as classes, they'll still be in a single string, for example: class: "class1 class2"
selfClosing
- true
or false
. Whether this tag has a self-closing slash such as: <img/>
, or <input/>
children
- it will still have a children
array, but it will always be empty.If this sounds interesting you should probably follow @HenrikJoreteg and @Philip_Roberts on twitter to see how this all turns out.
MIT
FAQs
Parses well-formed HTML (meaning all tags closed) into an AST and back. quickly.
The npm package html-parse-stringify receives a total of 2,880,715 weekly downloads. As such, html-parse-stringify popularity was classified as popular.
We found that html-parse-stringify demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 4 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
Security News
Members Hub is conducting large-scale campaigns to artificially boost Discord server metrics, undermining community trust and platform integrity.
Security News
NIST has failed to meet its self-imposed deadline of clearing the NVD's backlog by the end of the fiscal year. Meanwhile, CVE's awaiting analysis have increased by 33% since June.