kplattret
kplattret

Reputation: 57

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!

Upvotes: 4

Views: 8386

Answers (3)

Lee
Lee

Reputation: 10603

$("#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/

Upvotes: 7

Michal Klouda
Michal Klouda

Reputation: 14521

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.

Upvotes: 5

brightboy2004
brightboy2004

Reputation: 268

Replace your code with:

$(".map .tooltip-inner > h2").each(function() {
    var html = $(this).html().text();
    var result = html.replace(/\ /g,'<br/>'); 
    $(this).html(result);
});

Upvotes: -1

Related Questions