Insert a <br /> tag after x words using jQuery
javascript, jquery
Solution
$("#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/
Problem
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!