将此HTML作为字符串"html",如何将其拆分为一个数组,其中每个标题<h标记元素的开头?
从这开始:
<h1>A</h1>
<h2>B</h2>
<p>Foobar</p>
<h3>C</h3>
Run Code Online (Sandbox Code Playgroud)
结果:
["<h1>A</h1>", "<h2>B</h2><p>Foobar</p>", "<h3>C</h3>"]
Run Code Online (Sandbox Code Playgroud)
我尝试过的:
我想使用Array.split()正则表达式,但结果将每个都拆分<h为自己的元素.我需要弄清楚如何从一开始<h到下一个开始捕捉<h.然后包括第一个但排除第二个.
var html = '<h1>A</h1><h2>B</h2><p>Foobar</p><h3>C</h3>';
var foo = html.split(/(<h)/);
Run Code Online (Sandbox Code Playgroud)
编辑:Regex无论如何都不是必需的,它只是我认为通常以这种方式分割HTML字符串的唯一解决方案.
and*_*lrc 17
在您的示例中,您可以使用:
/
<h // Match literal <h
(.) // Match any character and save in a group
> // Match literal <
.*? // Match any character zero or more times, non greedy
<\/h // Match literal </h
\1 // Match what previous grouped in (.)
> // Match literal >
/g
Run Code Online (Sandbox Code Playgroud)
var str = '<h1>A</h1><h2>B</h2><p>Foobar</p><h3>C</h3>'
str.match(/<h(.)>.*?<\/h\1>/g); // ["<h1>A</h1>", "<h2>B</h2>", "<h3>C</h3>"]
Run Code Online (Sandbox Code Playgroud)
但请不要使用regexp解析HTML,请阅读除XHTML自包含标记之外的RegEx匹配开放标记
从评论到问题,这似乎是任务:
我正在采取动态降价,我正在从GitHub中搜集.然后我想将它呈现为HTML,但将每个title元素包装在ReactJS
<WayPoint>组件中.
以下是完全与库无关的基于DOM-API的解决方案.
function waypointify(html) {
var div = document.createElement("div"), nodes;
// parse HTML and convert into an array (instead of NodeList)
div.innerHTML = html;
nodes = [].slice.call(div.childNodes);
// add <waypoint> elements and distribute nodes by headings
div.innerHTML = "";
nodes.forEach(function (node) {
if (!div.lastChild || /^h[1-6]$/i.test(node.nodeName)) {
div.appendChild( document.createElement("waypoint") );
}
div.lastChild.appendChild(node);
});
return div.innerHTML;
}
Run Code Online (Sandbox Code Playgroud)
在具有较少代码行的现代库中执行相同操作绝对是可能的,将其视为挑战.
这是您通过示例输入生成的内容:
<waypoint><h1>A</h1></waypoint>
<waypoint><h2>B</h2><p>Foobar</p></waypoint>
<waypoint><h3>C</h3></waypoint>
Run Code Online (Sandbox Code Playgroud)