[英]Turn HTML string into a organized Object
朗:節點 JS
我正在使用文本編輯器,我得到了這樣的 output 字符串
<p>This is <strong>a <a href="#">test</a></strong></p>
但可能是不同的 HTML 標簽,如 H1、H2 等,但沒有什么比實際的 HTML 文本標簽更特別的了。
現在我想將該字符串轉換為 object,我可以使用它並將其發送到我的數據庫。 所以完美的方式是將它變成這樣的東西......
[{type: "text", text: "This is ", bold: false}, {type: "text", text: "a ", bold: true}, {type: "link", text: "test", bold: true, href: "#}]
等等。
我嘗試了正則表達式方法並將其拆分並執行各種邏輯以變成結構化的 object 但這不是最好的方法,因為如果我將來編寫<h1>Test</h1>
它會失敗<h1>Test</h1>
中間的文字為例。
你會如何處理這個問題?
如果你想 go 容易, jsdom
或htmlparser2
和domhandler
會幫助做到這一點。 例如,使用htmlparser2
和domhandler
(來自我的一些應用程序):
// Parsers helpers
import { Parser } from 'htmlparser2';
import { DomHandler } from 'domhandler';
// Get all text contents, recursively
const getAllText = (node) => {
return node.children.map( n => {
if (n.type === 'text') {
return n.data.trim("\n\r ");
}
// Discard `small` tags
if (n.name === 'small') {
return ''
}
return getAllText(n);
}).join('')
}
// Parses HTML data containing a UL/LI/A tree
const parseMenu = (data) => {
const parseLink = (link) => {
const name = getAllText(link);
const code = link.attribs['data-value']?.trim("\n\r ");
return {
name,
...(code ? {code} : {}),
}
}
const parseLi = (li) => {
const ul = li.children.find(({type, name}) => type === 'tag' && name === 'ul' );
const link = li.children.find(({type, name}) => type === 'tag' && name === 'a' );
return {
...(link ? parseLink(link) : {}),
...(ul ? {children: parseUl(ul)} : {}),
}
}
const parseUl = (ul) => {
return ul.children.filter(({type, name}) => type === 'tag' && name === 'li' ).map( child => {
return parseLi(child);
});
}
let result;
const handler = new DomHandler( (error, dom) => {
if (error) {
// Handle error
} else {
// Parsing completed, do something
result = parseUl(dom[0]);
}
});
const parser = new Parser(handler);
parser.write(data);
parser.end();
return result;
}
使用cheerio 庫(或您選擇的任何其他html 解析器庫)並根據需要操作“DOM 節點”object。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.