Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx in JavaScript .split()

I need to split up a string like this

<p>foo</p><p>bar</p>

to an array with "foo" and "bar"

I thought RegEx could help me, but it seems I didn't understand RegEx. This is my try.

var inputText = "<p>foo</p><p>bar</p>";
splittedSelection = inputText.split("/<p>|<\/p>/g");

But all I can achieve is an array with one entry and it's the same as the inputText.

I made a little fiddle for you.

Thanks for any help.

like image 478
Yashia Avatar asked Oct 17 '22 08:10

Yashia


1 Answers

You should use /<p>|<\/p>/g instead of inside quotations. However, this will produce ["", "foo", "", "bar", ""], which is undesirable, so you can .filter() out empty results, like this:

var inputText = "<p>foo</p><p>bar</p>";

splittedSelection = inputText.split(/<p>|<\/p>/g).filter(function(value) {
  // Filter out empty results
  return value !== "";
});

document.getElementById("bar").innerHTML += "0: " + splittedSelection[0] + "\n" + "1: " + splittedSelection[1] + "\n";
<div id="bar">
</div>
like image 191
Angelos Chalaris Avatar answered Oct 21 '22 04:10

Angelos Chalaris