Insert <br/"> tag after x using jQuery
I am trying to insert <br /> after 5 words in the title, but the piece of code that I use does not work. 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 tage t20 after the word first . But if I changed it to html.slice(5) , then it does not work properly.
How can I fix this so that it works fine after 5 words? Or maybe a different approach would be more appropriate? Thanks for your help in advance!
$("#post-id > h2").each(function() { var html = $(this).html().split(" "); html = html.slice(0,5).join(" ") + "<br />" + html.slice(5).join(" "); $(this).html(html); }); The main idea is that you take the first 5 words using slicing from zero index and get 5 elements of the array, attach them, add your break tag, then get the remaining elements in the array with index 5 (like its zero based on the index) and connect them with spaces and unload it at the end
change
for a complete answer, and if the OP wants to break after every 5 words, here is 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(" ")); });