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>
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);
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.