将字符串标记与字符串中的文本分开

时间:2018-01-03 15:26:28

标签: javascript regex

假设我们有以下字符串:

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. 

<script src="http://foo.com/script.js"></script>

Etiam porta sem malesuada magna mollis euismod. Vestibulum id ligula porta felis euismod semper. 

<script>var x = 'a';</script>

Nulla vitae elit libero, a pharetra augue. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

我希望将其拆分为一个数组,其内容如下:

[
  "Praesent commodo cursus magna, vel scelerisque nisl consectetur et.\n\n",
  "<script src="http://foo.com/script.js"></script>",
  "\n\nEtiam porta sem malesuada magna mollis euismod. Vestibulum id ligula porta felis euismod semper.\n\n",
  "<script>var x = 'a';</script>",
  "\n\nNulla vitae elit libero, a pharetra augue. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.",
]

例如将脚本标签与普通标签分开并将它们全部放在一个数组中,我该怎么做?

1 个答案:

答案 0 :(得分:0)

好的,明白了:

const embedCode = "...text from above"
const r = /(<script.*?<\/script>)/
console.log(embed.split(r));