简体   繁体   中英

How can I split a text node into spans of 3 words each?

Let's say I have this div:

<div> Let's say these are the words in my div </div>

I know I can wrap every words in the div into a span this way

$("div").contents().wrap('<span class="wrapper"/>');
//output:  <div><span class="wrapper"> Let's say these are the words in my div</span> </div>

However, I would like to achieve this instead:

<div>
    <span class="wrapper">Let's say these</span>
    <span class="wrapper">are the words</span>
    <span class="wrapper">in my div</span>
</div>

Every particular amount of words (this case: every 3 words) are to be divided into a group and each group of words is to be wrapped separately.


These are what first come to my mind:

1) I think it can be achieved by using text() to obtain the string and split(' ') it to form an array with each element contains a word, write a while loop to manipulate the array:

var a = 0;
var b = array.length;
while (a<b) {
    array[a] = "<span class="wrapper>" +  array[a]";
    a +=2;
    if (a>b) {
        a = b-1;
    }
    array[a] = array[a] + "</span>";
    a++;
}

then just simply .join('') the array to form a string and $("div").html(string) ;


2) Or I can simply use regular expression after obtaining with text() :

do a global search for expressions containing a word + a space + a word + a space + another word

/(\\w+\\s+\\w+\\s+\\w+)/g

replace it with it wrapped in a span

<span>$1</span>

and html() the output before performing a $("div").contents().eq(2).wrap('<span class="wrapper"/>') for the odd one out if there is any.


These are what I've come up with and I want to know, are there better ways other than these?

And what's the best way (fastest & require least memory) to achieve it?

This ought to do what you want:

Demo here: http://jsfiddle.net/UQk7r/

$("div").each(function() {
    var out = [];
    var words = $(this).text()..trim().split(' ');
    for (var i = 0; i < words.length; i += 3) {
        out.push('<span class="wrapper">' + words.slice(i, i+3).join(' ') + '</span>');
    }
    $(this).html(out.join(' '));
});

Here's the DOM version (no jQuery):

Demo here: http://jsfiddle.net/cCege/2/

var divs = document.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
    var out = [];
    var words = divs[i].innerText.trim().split(' ');
    for (var j = 0; j < words.length; j += 3) {
        out.push('<span class="wrapper">' + words.slice(j, j+3).join(' ') + '</span>');
    }
    divs[i].innerHTML = out.join(' ');
}

Finally, here's a DOM + RegEx version... this should be your optimal performer:

Demo: http://jsfiddle.net/Xgm5q/1/

var divs = document.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
    divs[i].innerHTML = '<span class="wrapper">' 
            + divs[i].innerText.trim().replace(/(([^\s]+\s+){2}[^\s]+)\s+/g, '$1</span> <span class="wrapper">')
            + '</span>';
}​

For performance :

var elems = document.getElementsByTagName('div');

for (var j=elems.length; j--;) {
    var txtArr = elems[j].textContent.replace(/([a-zA-Z]+)\s([a-zA-Z]+)\s([a-zA-Z]+)/g, '$1 $2 $3* ').split('*'),
        txtElm = document.createDocumentFragment(),
        span   = document.createElement('span');

    for (i=0; i<txtArr.length; i++) {
        if (/\S/.test(txtArr[i])) {
            var sp   = span.cloneNode(true),
                text = document.createTextNode(txtArr[i]);

            sp.appendChild(text);
            txtElm.appendChild(sp);
        }
    }

    elems[j].innerHTML = '';
    elems[j].appendChild(txtElm)
}
​

FIDDLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM