开发者

Separate each word from an element with a string sentence, but there are some spans

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 sur开发者_运维问答e I'm missing something. Any ideas?

Thanks


The spans make it messy; you have turn the spans into spaces, then split on space.

var array = $('h1').html().replace(/\<\/*span\>/g,' ').split(' ');


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


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+/ );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜