3 回答
TA贡献1809条经验 获得超8个赞
不要在HTML(或HTML的任何表兄弟)上使用RegEx。将您收集<section>s到NodeList中。将该NodeList转换为数组。将每个节点转换为字符串。这可以在一行中完成:
const strings = Array.from(document.querySelectorAll('section')).map(section => section.outerHTML);
以下演示是上述示例的细分。
// Collect all <section>s into a NodeList
const sections = document.querySelectorAll('section');
// Convert NodeList into an Array
const array = Array.from(sections);
/*
Iterate through Array -- on each <section>...
convert it into a String
*/
const strings = array.map(section => section.outerHTML);
// View array as a template literal for a cleaner look
console.log(`${strings}`);
// Verifying it's an array of mutiple elements
console.log(strings.length);
// Verifying that they are in fact strings
console.log(typeof strings[0]);
<chapter id="chap1">
<para0>
<title></title>
</para0>
</chapter>
<chapter id="chap2">
<title>THEORY</title>
<section id="Thoery">
<title>theory Section</title>
<para0 verstatus="ver">
<title>Theory Para 0 </title>
<text>blah blah</text>
</para0>
</section>
<section id="Next section">
<title>title</title>
<para0>
<title>Title</title>
<text>blah blah</text>
</para0>
</section>
<section id="More sections">
<title>title</title>
<para0>
<title>Title</title>
<text>blah blah</text>
</para0>
</section>
<section id="section">
<title>title</title>
<para0>
<title>Title</title>
<text>blah blah</text>
</para0>
</section>
<chapter id="chap1">
<para0>
<title></title>
</para0>
</chapter>
<chapter id="chap1">
<para0>
<title></title>
</para0>
</chapter>
<chapter>
<title>Chapter Title</title>
<section id="Section ID">
<title>Section Title</title>
<para0>
<title>Para0 Title</title>
<para>blah blah</para>
</para0>
</section>
<section id="Next section">
<title>title</title>
<para0>
<line>Title</line>
<text>blah blah</text>
</para0>
</section>
<section id="More sections">
<title>title</title>
<para0>
<list>Title</list>
<text>blah blah</text>
</para0>
</section>
<section id="section">
<title>title</title>
<para0>
<title>Title</title>
<text>blah blah</text>
</para0>
</section>
<ipbchap>
<tags></tags>
</ipbchap>
TA贡献1860条经验 获得超9个赞
您不需要拆分字符串 - 您希望从中提取与您的模式匹配的数据。你可以使用String#match
。请注意,您需要添加g
标志以获取所有匹配项:
但是,最好解析DOM并从中提取所需的信息 - 这很简单DOMParser
:
添加回答
举报