Split a string of HTML into an array by particular tags

后端 未结 4 766
遇见更好的自我
遇见更好的自我 2021-01-05 00:41

Given this HTML as a string \"html\", how can I split it into an array where each header marks the start of an element?

Begin with this:

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-05 01:09

    I'm sure someone could reduce the for loop to put the angle brackets back in but this is how I'd do it.

    var html = '

    A

    B

    Foobar

    C

    '; //split on >< var arr = html.split(/>< 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] + '>'; } }

    Additionally, we could actually remove the first and last bracket, do the split and then replace the angle brackets to the whole thing.

    var html = '

    A

    B

    Foobar

    C

    '; //remove first and last characters html = html.substring(1, html.length-1); //do the split on >< var arr = html.split(/>'; }

    Oh, of course this will fail with elements that have no content.

提交回复
热议问题