我正在将wysiwyg生成的内容解析到React中的目录小部件中。
到目前为止,我遍历头文件并将它们添加到一个数组中。
我怎样才能把它们都放到一个多维数组或对象中(最好的方法是什么),让它看起来更像:
h1-1
h2-1
h3-1
h1-2
h2-2
h3-2
h1-3
h2-3
h3-3然后我可以在UI中用有序列表呈现它。
const str = "<h1>h1-1</h1><h2>h2-1</h2><h3>h3-1</h3><p>something</p><h1>h1-2</h1><h2>h2-2</h2><h3>h3-2</h3>";
const patternh1 = /<h1>(.*?)<\/h1>/g;
const patternh2 = /<h2>(.*?)<\/h2>/g;
const patternh3 = /<h3>(.*?)<\/h3>/g;
let h1s = [];
let h2s = [];
let h3s = [];
let matchh1, matchh2, matchh3;
while (matchh1 = patternh1.exec(str))
h1s.push(matchh1[1])
while (matchh2 = patternh2.exec(str))
h2s.push(matchh2[1])
while (matchh3 = patternh3.exec(str))
h3s.push(matchh3[1])
console.log(h1s)
console.log(h2s)
console.log(h3s)
发布于 2018-05-20 04:43:18
我不知道你是怎么想的,但我讨厌用正则表达式解析HTML。相反,我认为让DOM处理这件事是更好的主意:
const str = `<h1>h1-1</h1>
<h3>h3-1</h3>
<h3>h3-2</h3>
<p>something</p>
<h1>h1-2</h1>
<h2>h2-2</h2>
<h3>h3-2</h3>`;
const wrapper = document.createElement('div');
wrapper.innerHTML = str.trim();
let tree = [];
let leaf = null;
for (const node of wrapper.querySelectorAll("h1, h2, h3, h4, h5, h6")) {
const nodeLevel = parseInt(node.tagName[1]);
const newLeaf = {
level: nodeLevel,
text: node.textContent,
children: [],
parent: leaf
};
while (leaf && newLeaf.level <= leaf.level)
leaf = leaf.parent;
if (!leaf)
tree.push(newLeaf);
else
leaf.children.push(newLeaf);
leaf = newLeaf;
}
console.log(tree);
这个答案并不要求h3遵循h2;如果你愿意,h3可以遵循h1。如果您想将其转换为有序列表,也可以这样做:
const str = `<h1>h1-1</h1>
<h3>h3-1</h3>
<h3>h3-2</h3>
<p>something</p>
<h1>h1-2</h1>
<h2>h2-2</h2>
<h3>h3-2</h3>`;
const wrapper = document.createElement('div');
wrapper.innerHTML = str.trim();
let tree = [];
let leaf = null;
for (const node of wrapper.querySelectorAll("h1, h2, h3, h4, h5, h6")) {
const nodeLevel = parseInt(node.tagName[1]);
const newLeaf = {
level: nodeLevel,
text: node.textContent,
children: [],
parent: leaf
};
while (leaf && newLeaf.level <= leaf.level)
leaf = leaf.parent;
if (!leaf)
tree.push(newLeaf);
else
leaf.children.push(newLeaf);
leaf = newLeaf;
}
const ol = document.createElement("ol");
(function makeOl(ol, leaves) {
for (const leaf of leaves) {
const li = document.createElement("li");
li.appendChild(new Text(leaf.text));
if (leaf.children.length > 0) {
const subOl = document.createElement("ol");
makeOl(subOl, leaf.children);
li.appendChild(subOl);
}
ol.appendChild(li);
}
})(ol, tree);
// add it to the DOM
document.body.appendChild(ol);
// or get it as text
const result = ol.outerHTML;
由于HTML是由DOM解析的,而不是由正则表达式解析的,例如,如果h1标记具有属性,则此解决方案不会遇到任何错误。
发布于 2018-05-20 02:19:06
您可以简单地收集所有h*,然后迭代它们来构建一个树:
使用ES6 (我从const和let的用法推断出这是可以的)
const str = `
<h1>h1-1</h1>
<h2>h2-1</h2>
<h3>h3-1</h3>
<p>something</p>
<h1>h1-2</h1>
<h2>h2-2</h2>
<h3>h3-2</h3>
`
const patternh = /<h(\d)>(.*?)<\/h(\d)>/g;
let hs = [];
let matchh;
while (matchh = patternh.exec(str))
hs.push({ lev: matchh[1], text: matchh[2] })
console.log(hs)
// constructs a tree with the format [{ value: ..., children: [{ value: ..., children: [...] }, ...] }, ...]
const add = (res, lev, what) => {
if (lev === 0) {
res.push({ value: what, children: [] });
} else {
add(res[res.length - 1].children, lev - 1, what);
}
}
// reduces all hs found into a tree using above method starting with an empty list
const tree = hs.reduce((res, { lev, text }) => {
add(res, lev-1, text);
return res;
}, []);
console.log(tree);但是因为你的html头文件本身不是树形结构(我猜这是你的用例),所以这只在某些假设下有效,例如,你不能有一个<h3>,除非在它上面有一个<h2>,在它上面有一个<h1>。它还将假设较低级别的标头始终属于紧随其后的较高级别的最新标头。
如果您想要进一步使用树结构来呈现TOC的代表性有序列表,您可以这样做:
// function to render a bunch of <li>s
const renderLIs = children => children.map(child => `<li>${renderOL(child)}</li>`).join('');
// function to render an <ol> from a tree node
const renderOL = tree => tree.children.length > 0 ? `<ol>${tree.value}${renderLIs(tree.children)}</ol>` : tree.value;
// use a root node for the TOC
const toc = renderOL({ value: 'TOC', children: tree });
console.log(toc);希望能有所帮助。
发布于 2018-05-20 18:56:29
你要做的就是(文档大纲的变体),例如。从文档标题创建嵌套列表,遵循文档的层次结构。
使用DOM和HTML的浏览器的一个简单实现如下所示(放在一个DOMParser页面中,并用ES5编码以便于测试):
<!DOCTYPE html>
<html>
<head>
<title>Document outline</title>
</head>
<body>
<div id="outline"></div>
<script>
// test string wrapped in a document (and body) element
var str = "<html><body><h1>h1-1</h1><h2>h2-1</h2><h3>h3-1</h3><p>something</p><h1>h1-2</h1><h2>h2-2</h2><h3>h3-2</h3></body></html>";
// util for traversing a DOM and emit SAX startElement events
function emitSAXLikeEvents(node, handler) {
handler.startElement(node)
for (var i = 0; i < node.children.length; i++)
emitSAXLikeEvents(node.children.item(i), handler)
handler.endElement(node)
}
var outline = document.getElementById('outline')
var rank = 0
var context = outline
emitSAXLikeEvents(
(new DOMParser()).parseFromString(str, "text/html").body,
{
startElement: function(node) {
if (/h[1-6]/.test(node.localName)) {
var newRank = +node.localName.substr(1, 1)
// set context li node to append
while (newRank <= rank--)
context = context.parentNode.parentNode
rank = newRank
// create (if 1st li) or
// get (if 2nd or subsequent li) ol element
var ol
if (context.children.length > 0)
ol = context.children[0]
else {
ol = document.createElement('ol')
context.appendChild(ol)
}
// create and append li with text from
// heading element
var li = document.createElement('li')
li.appendChild(
document.createTextNode(node.innerText))
ol.appendChild(li)
context = li
}
},
endElement: function(node) {}
})
</script>
</body>
</html>我首先将片段解析为Document,然后遍历它以创建类似SAX的startElement()调用。在startElement()函数中,根据最近创建的列表项(如果有)的排名检查标题元素的排名。然后,在正确的层次结构级别附加一个新的列表项,并可能创建一个ol元素作为它的容器。请注意,该算法不适用于层次结构中从h1到h3的“跳转”,但可以很容易地进行调整。
如果您想在node.js上创建大纲/目录,可以使代码运行在服务器端,但需要一个像样的HTML解析库(可以说是node.js的DOMParser polyfill )。还有用于创建大纲的https://github.com/h5o/h5o-js和https://github.com/hoyois/html5outliner包,尽管我还没有对它们进行测试。据推测,这些包还可以处理边角情况,比如iframe和quote元素中的标题元素,这些元素通常不希望出现在文档的大纲中。
创建HTML5大纲的主题有很长的历史;参见例如。http://html5doctor.com/computer-says-no-to-html5-document-outline/。HTML4不使用分段根(在HTML5中)包装器元素来进行分段,并将标题和内容放在相同的层次结构级别,这种做法被称为“扁平式标记”。SGML具有用于处理H1、H2等排序元素的RANK功能,并且可以推断省略的section元素,从而在简单的情况下自动从类似HTML4的“扁平地球标记”创建轮廓(例如。其中只允许section或另一单个元素作为分段根)。
https://stackoverflow.com/questions/50385899
复制相似问题