Reputation: 853
I'm feeling a little newbie with this problem...
Ok, facing this example:
<h1>A<span>really</span>long<span>sentence</span></h1>
I need to dynamically place each word in an array, however i need to keep the order. Something like:
var words = ['A','really','long','sentence'];
My original idea was to get all spans into an array, and all words without span into another array, and then merge both, however, i'm not seeing any javascript/jQuery method to properly collect the words without spans into an array.
I'm sure I'm missing something. Any ideas?
Thanks
Upvotes: 0
Views: 268
Reputation: 19560
While it is always best to use plain JS where possible, it is also a nasty thing to try to parse HTML reliably. Since jQ is already in use here, I'd stick with $.fn.text():
var a = $( '<h1>A <span>really</span> long <span>sentence</span></h1>' ).text().split( /\W+/ );
Upvotes: 0
Reputation: 104770
function wordgrab(node){
var A= [];
if(node){
node= node.firstChild;
while(node!= null){
if(node.nodeType== 3){
if(/[a-zA-Z]/.test(node.data)){
A= A.concat(node.data.split(/\s+/));
}
}
else A= A.concat(wordgrab(node));
node= node.nextSibling;
}
}
return A;
}
wordgrab(document.body)// use any parent node
Upvotes: 0
Reputation: 1238
The spans make it messy; you have turn the spans into spaces, then split on space.
var array = $('h1').html().replace(/\<\/*span\>/g,' ').split(' ');
Upvotes: 3