tag after x using jQuery I am trying to insert
after 5 words in the title, but the piece of code that I use does not work. See...">

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!

+4
source share
3 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/

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(" ")); });​ 

http://jsfiddle.net/2Z2nM/

+7
source

You can simplify the code:

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

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

+4
source

Replace the code:

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

Source: https://habr.com/ru/post/1441555/


All Articles