LeRoy
LeRoy

Reputation: 4456

Get the text between two custom tags from a string using regex

I have a string that I want to get text from:

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"

I want to get the text from all the <custom /> tags in a array. I am trying to get this result:

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

How can I do this?

Upvotes: 0

Views: 151

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337714

Firstly, never ever use RegEx to parse HTML. To achieve this you can create a jQuery object from the text and then filter() out the custom elements before creating an array of their text using map(). Try this:

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

Working example

Upvotes: 3

Related Questions