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!
$("#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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With