Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert a <br /> tag after x words using jQuery

I am trying to insert a <br /> after 5 words in a title, but the piece of code I'm using doesn't work. Please see below:

$("#post-id > h2").each(function() {
    var html = $(this).html().split(" ");
    html = html[0] + "<br />" + html.slice(1).join(" ");
    $(this).html(html);
});

This function works well as it is - if you want to add a <br /> tage after the first word. But if I change it to html.slice(5) then it doesn't work properly.

How could I fix this so it works fine after 5 words? Or maybe a different approach would be more appropriate? Thanks for your help in advance!

like image 721
kplattret Avatar asked Dec 20 '22 14:12

kplattret


2 Answers

$("#post-id > h2").each(function() {
     var html = $(this).html().split(" ");
     html = html.slice(0,5).join(" ") + "<br />" + html.slice(5).join(" ");
     $(this).html(html);
});​

http://jsfiddle.net/f4chL/

Basic idea is you take the first 5 words via slicing from index zero, and getting 5 elements of the array, join them, add your break tag, then get the remaining elements in the array at index 5 (as its a zero based index) and join them with spaces and dump it on the end

edit

for the sake of a full answer and if the OP does want to split after every 5 words, here's another method

$("h2").each(function() {
var html = $(this).html().split(" ");
var newhtml = [];

for(var i=0; i< html.length; i++) {

    if(i>0 && (i%5) == 0)
        newhtml.push("<br />");

    newhtml.push(html[i]);
}

$(this).html(newhtml.join(" "));
});​

http://jsfiddle.net/2Z2nM/

like image 171
Lee Avatar answered Jan 02 '23 20:01

Lee


You could simplify your code to:

.replace(/((\w+\W+){5})/, '$1<br/>')

See this FIDDLE. Depending on your definition of word, you can change the \w+ to whatever suits you.

like image 32
Michal Klouda Avatar answered Jan 02 '23 22:01

Michal Klouda