Behseini Behseini - 5 months ago 9
jQuery Question

jQuery Grab Text inside a Tag in String Format and Add to Array

I have string which is like

Lorem Ipsum is simply dummy text of the printing and typesetting
industry.<grab> First Item</grab>Lorem Ipsum is simply dummy text of
the printing and typesetting industry.<grab>Second Item</grab>Lorem
Ipsum is simply dummy text of the printing and typesetting
industry.<grab>Third Item</grab>Lorem Ipsum is simply dummy text of
the printing and typesetting industry.


now I need to grab all text between the
<grab>....</grab>
tags and add them two an array. I tried this but it didnt go through



var data = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.<grab> First Item</grab>Lorem Ipsum is simply dummy text of the printing and typesetting industry.<grab>Second Item</grab>Lorem Ipsum is simply dummy text of the printing and typesetting industry.<grab>Third Item</grab>Lorem Ipsum is simply dummy text of the printing and typesetting industry.';

var array = $('<grab>').map(function() {
return $(this).text();
}).get();
$('body').append(array);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>





Can you please let me know how to do this

Answer

Those are not DOM elements actually, so probably regex would help you.

var data = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.<grab> First Item</grab>Lorem Ipsum is simply dummy text of the printing and typesetting industry.<grab>Second Item</grab>Lorem Ipsum is simply dummy text of the printing and typesetting industry.<grab>Third Item</grab>Lorem Ipsum is simply dummy text of the printing and typesetting industry.';
var r = /<grab>(.*?)<\/grab>/g;
var grabs = data.match(r).map(function(x){
   return x.replace(r,'$1');
});
console.log(grabs);