qadenza
qadenza

Reputation: 9293

how to split a string by the first instance of '<p>'

in the example below I need to split the string by the first instance of <p>
so the first element should be lorem ipsum and the second one - everything behind

var str = "lorem ipsum<p>dolor sit</p><p>amet</p>";
var start = str.split("<p>:first")[0]; // something like that
console.log(start); // should be `lorem ipsum`
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 0

Views: 90

Answers (2)

ibrahim mahrir
ibrahim mahrir

Reputation: 31692

split by all the "<p>" instances then take the first one and join the rest by "<p>", use a destructring assignment to make things simple like so:

let [start, ...rest] = str.split("<p>");
rest = rest.join("<p>");

Demo:

var str = "lorem ipsum<p>dolor sit</p><p>amet</p>";

let [start, ...rest] = str.split("<p>");
rest = rest.join("<p>");

console.log("start: " + start);
console.log("rest: " + rest);

Upvotes: 3

CertainPerformance
CertainPerformance

Reputation: 370789

Make everything that comes after the <p> a capturing group, and it'll be included in the match as another item:

var str = "lorem ipsum<p>dolor sit</p><p>amet</p>";
var start = str.split(/<p>(.*)/).filter(Boolean);
console.log(start); // should be `lorem ipsum`
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 2

Related Questions