TheRed
TheRed

Reputation: 327

JS split method, include separator in array

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>

Upvotes: 2

Views: 1368

Answers (2)

Oka
Oka

Reputation: 26355

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)

Upvotes: 3

Darshan
Darshan

Reputation: 1074

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)

Upvotes: 0

Related Questions