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>
1
  • 2
    You should parse it as HTML instead of trying to split. Commented Feb 28, 2016 at 18:35

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.