Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

string - jQuery: wrap every nth word in a span

Is it possible in jquery to wrap each nth word in a span

so lets say I have the html string

<h3>great Prices great Service</h3> 

this will be wrapped as follows ( each 2nd word )

<h3>great <span>Prices</span> great <span>Service</span></h3> 

Any help will be appreciated

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
var h3 = $('h3');
var text = h3.text().split(' ');

for( var i = 1, len = text.length; i < len; i=i+2 ) {
    text[i] = '<span>' + text[i] + '</span>';
}
h3.html(text.join(' '));

http://jsfiddle.net/H5zzq/

or

var h3 = $('h3');
var text = h3.text().split(' ');

$.each(text,function(i,val) {
    if( i % 2) {
        text[i] = '<span>' + val + '</span>';
    }
});
h3.html(text.join(' '));

http://jsfiddle.net/H5zzq/1


To deal with & as you requested in your comment, I created an offset variable that is incremented whenever one is encountered.

var h3 = $('h3');
var text = h3.text().split(' ');
var offset = 0;

for( var i = 1, len = text.length; i < len; i++ ) {
    if( text[i] === '&' ) {
        offset++;
    } else if( (i-offset) % 2 ) {
        text[i] = '<span>' + text[i] + '</span>';
    }
}
h3.html(text.join(' '));

http://jsfiddle.net/H5zzq/3


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...