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/
Here’s the DOM version (no jQuery):
Demo here: http://jsfiddle.net/cCege/2/
Finally, here’s a DOM + RegEx version… this should be your optimal performer:
Demo: http://jsfiddle.net/Xgm5q/1/