使用正则表达式从字符串中获取两个自定义标记之间的文本

时间:2016-03-04 09:05:01

标签: jquery regex

我有一个字符串,我想从中获取文字:

var text = "<p>This is awesome and</p> <p>some random</p> and <custom>complex boring text</custom> <p>I</p> <custom>really need to clean</custom> up my room. that feel"

我想从数组中的所有<custom />标记中获取文本。我想得到这个结果:

['complex boring text', 'really need to clean']

我该怎么做?

1 个答案:

答案 0 :(得分:3)

首先,never ever use RegEx to parse HTML。为了实现这一点,您可以使用text创建一个jQuery对象,然后filter()创建custom元素,然后使用map()创建一个文本数组。试试这个:

var arr = $(text).filter('custom').map(function() {
    return $(this).text();
}).get();
console.log(arr);

Working example