简体   繁体   中英

JavaScript - splitting a string on specific character

I am returning data from a database that I am attempting to split. I have a string data that consists of a couple of html tags and text. I will appending these lines of text individually so I am attempting to separate each time the </p> tag appears. For example:

data = '<p>Estimated Revenue for Online Stores in 2020 </p><p>The sales of online stores has increased by 2.7% over the past few months.</p> <p>There is an increase of 3.1% of sales compared to the total sales amount of 2019.</p>'

I've attempted this by using data.split('</p>') which does split the text where I am expecting it, but it is not including the closing </p> tag that I am doing the split method on. Is there an alternative method that I can use or alter the existing .split method that will accomplish the same idea but return the closing </p> tag?

Here is a snippet of my code:

 data = '<p>Estimated Revenue for Online Stores in 2020 </p><p>The sales of online stores has increased by 2.7% over the past few months.</p> <p>There is an increase of 3.1% of sales compared to the total sales amount of 2019.</p>' let splitData = data.split('</p>') console.log(splitData)

I am expecting an outcome like :

  "<p>Estimated Revenue for Online Stores in 2020 </p>",
  "<p>The sales of online stores has increased by 2.7% over the past few months.</p>",
  "<p>There is an increase of 3.1% of sales compared to the total sales amount of 2019.</p>"

This should do it:

data = '<p>Estimated Revenue for Online Stores in 2020 </p><p>The sales of online stores has increased by 2.7% over the past few months.</p> <p>There is an increase of 3.1% of sales compared to the total sales amount of 2019.</p>'

let splitData = data.split('</p>').map(e=>e+"</p>")

splitData.pop()

console.log(splitData)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM