2

I would like to split a set of div elements, for further text-processing in an array. A simple mockup:

var divElements = prompt('Input');
array = divElements.split('</div>')
console.log(array);

Input:

<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<div id="4"></div>

Output for now:

array
["<div id="1">", "
<div id="2">", "
<div id="3">", "
<div id="4">", ""]

but I would like to include the separator (div closing tag) inside the array to keep the html syntax intact. As a result the array should have these four items:

<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<div id="4"></div>
TheRed
  • 317
  • 3
  • 12

2 Answers2

3

You can also use a regular expression, to look ahead for the next div.

var str = '<div id="1"></div><div id="2"></div><div id="3"></div><div id="4"></div>';

var arr = str.split(/(?=<div)/);

console.log(arr);

If you want to separate but keep the delimiter, you can use capturing parenthesis.

var str = '<div id="1"></div><div id="2"></div><div id="3"></div><div id="4"></div>';

var arr = str.split(/(<\/div>)/);

console.log(arr);

That said, you really should not do string operations, or regular expression parsing, on data that you know is HTML. Attributes might contain HTML-like patterns, and then you're out of luck.

Plunk it into a container element, and work on it that way, or use a proper parser.

var data = '<div id="1"></div><div id="2"></div><div id="3"></div><div id="4"></div>';

var ele = document.createElement('div');

ele.innerHTML = data;

console.log(ele.childNodes)
Community
  • 1
  • 1
Oka
  • 23,367
  • 6
  • 42
  • 53
0

split() method also takes regex to split strings. In your case use the regex \s(?=\<).

    var divElements = prompt('Input');
    array = divElements.split(/\s(?=\<)/);
    console.log(array);

regex explantion

  • \s - any space character
  • (?=\<) - followed by < character (positive look ahead)
Darshan
  • 1,064
  • 7
  • 15