jQuery: wrap every nth word in a span

后端 未结 2 1178
傲寒
傲寒 2020-12-18 13:52

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

so lets say I have the html string

great Prices great Service

2条回答
  •  攒了一身酷
    2020-12-18 14:37

    var h3 = $('h3');
    var text = h3.text().split(' ');
    
    for( var i = 1, len = text.length; i < len; i=i+2 ) {
        text[i] = '' + text[i] + '';
    }
    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] = '' + val + '';
        }
    });
    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] = '' + text[i] + '';
        }
    }
    h3.html(text.join(' '));
    

    http://jsfiddle.net/H5zzq/3

提交回复
热议问题