JavaScript-在特定字符上分割字符串

时间:2020-08-25 22:29:33

标签: javascript html

我正在从尝试拆分的数据库返回数据。我有一个字符串data,它由几个html标签和文本组成。我将逐行附加这些文本行,因此,每次出现</p>标签时,我都试图将其分开。例如:

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>'

我已经尝试过使用data.split('</p>')进行此操作,该操作确实在期望的位置拆分了文本,但其中不包括我正在执行split方法的结束</p>标记。有没有其他方法可以使用或更改现有的.split方法来实现相同的想法,但返回结束</p>标签呢?

这是我的代码的片段:

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)

我期望的结果是:

  "<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>"

1 个答案:

答案 0 :(得分:0)

这应该做到:

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)