Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/413.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 通过特定标记将HTML字符串拆分为数组_Javascript_Regex - Fatal编程技术网

Javascript 通过特定标记将HTML字符串拆分为数组

Javascript 通过特定标记将HTML字符串拆分为数组,javascript,regex,Javascript,Regex,假设这个HTML是一个字符串“HTML”,我如何将它拆分成一个数组,其中每个头我相信有人可以减少for循环,将尖括号放回,但我会这样做 var html = '<h1>A</h1><h2>B</h2><p>Foobar</p><h3>C</h3>'; //split on >< var arr = html.split(/></g); //split removes the

假设这个HTML是一个字符串“HTML”,我如何将它拆分成一个数组,其中每个头
我相信有人可以减少for循环,将尖括号放回,但我会这样做

var html = '<h1>A</h1><h2>B</h2><p>Foobar</p><h3>C</h3>';

//split on ><
var arr = html.split(/></g);

//split removes the >< so we need to determine where to put them back in.
for(var i = 0; i < arr.length; i++){
  if(arr[i].substring(0, 1) != '<'){
    arr[i] = '<' + arr[i];
  }

  if(arr[i].slice(-1) != '>'){
    arr[i] = arr[i] + '>';
  }
}
var html='ABFoobar

C'; //拆分时间>< var arr=html.split(/><因此我们需要确定将它们放回何处。 对于(变量i=0;i
此外,我们实际上可以删除第一个和最后一个括号,进行拆分,然后将角括号全部替换

var html = '<h1>A</h1><h2>B</h2><p>Foobar</p><h3>C</h3>';

//remove first and last characters
html = html.substring(1, html.length-1);

//do the split on ><
var arr = html.split(/></g);

//add the brackets back in
for(var i = 0; i < arr.length; i++){
    arr[i] = '<' + arr[i] + '>';
}
var html='ABFoobar

C'; //删除第一个和最后一个字符 html=html.substring(1,html.length-1); //在><
var arr=html.split(/>在您的示例中,您可以使用:

/
  <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
/

从对问题的评论来看,这似乎是一项任务:

我从GitHub中抓取动态标记,然后我想将其呈现为HTML,但将每个title元素包装在一个ReactJS
组件中

下面是一个完全与库无关的、基于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;
}
函数waypointify(html){
var div=document.createElement(“div”),节点;
//解析HTML并转换为数组(而不是NodeList)
div.innerHTML=html;
nodes=[].slice.call(div.childNodes);
//添加元素并按标题分布节点
div.innerHTML=“”;
forEach(函数(节点){
如果(!div.lastChild | |/^h[1-6]$/i.test(node.nodeName)){
div.appendChild(document.createElement(“航路点”);
}
div.lastChild.appendChild(节点);
});
返回div.innerHTML;
}
在代码行数较少的现代库中执行同样的操作是绝对可能的,将其视为一项挑战

这是它使用示例输入生成的结果:

<waypoint><h1>A</h1></waypoint>
<waypoint><h2>B</h2><p>Foobar</p></waypoint>
<waypoint><h3>C</h3></waypoint>
A
BFoobar

C
您好,我使用此函数转换数组中的html字符串Dom

  static getArrayTagsHtmlString(str){
    let htmlSplit = str.split(">")
    let arrayElements = []
    let nodeElement =""
    htmlSplit.forEach((element)=>{  
      if (element.includes("<")) {
        nodeElement = element+">"   
       }else{
         nodeElement = element
        }
        arrayElements.push(nodeElement)
    })
    return arrayElements
  }
静态getArrayTagsHtmlString(str){
设htmlSplit=str.split(“>”)
设arrayElements=[]
让nodeElement=“”
htmlSplit.forEach((元素)=>{
if(element.includes)(“)
}否则{
nodeElement=元素
}
arrayElements.push(节点元素)
})
返回阵列
}

Happy code

为什么要使用正则表达式呢?如果有一种方法不使用正则表达式,我完全愿意使用它:)你使用的是世界上最先进的HTML解析器托管的语言,不使用这些HTML解析功能有点傻。还有什么工作,请解释。(这是一个XY问题,即您已经决定了一个解决方案,不再费心解释任务。请解释任务本身,而不是预期的解决方案。)@DonnyP Check out
document.createDocumentFragment()
这是一个令人惊讶的SO问题/答案。反对将正则表达式推广到HTML问题。以你的声誉,你应该知道更多。@DonnyP这不是code golf。“在一行中完成”不是它的目标。他的答案不适合这个问题。HTML不能用正则表达式处理。这会崩溃和烧坏,等你在实际代码中试用时再看。@DonnyP我想你明白了!我向你展示了你的示例数据是可能的,但我也警告你应该重新考虑你的方法,特别是当你不知道你在处理什么数据时。请随意尝试看看它是否在你所有的数据集上都有效。如果有效,那就太好了!但如果无效,那仅仅是因为你试图用水来点火:-)@DonnyP HTML不是“太多变”。HTML属于一类语言(非常规)正则表达式本身无法描述。这是正则表达式的一个严格的技术限制。无论如何,尝试这样做意味着两件事之一:要么将自己限制为可以描述为正则语言的严格HTML子集(如果不这样做,则从GitHub中删除未知代码),或者您的代码中存在一个令人讨厌的单行程序错误。我想知道“但它只有一行!”是否是后一种情况的充分理由。如果使用“向前看”,您实际上可以保留正在查找的分隔符:
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>"]
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;
}
<waypoint><h1>A</h1></waypoint>
<waypoint><h2>B</h2><p>Foobar</p></waypoint>
<waypoint><h3>C</h3></waypoint>
  static getArrayTagsHtmlString(str){
    let htmlSplit = str.split(">")
    let arrayElements = []
    let nodeElement =""
    htmlSplit.forEach((element)=>{  
      if (element.includes("<")) {
        nodeElement = element+">"   
       }else{
         nodeElement = element
        }
        arrayElements.push(nodeElement)
    })
    return arrayElements
  }