Jquery uses "count" instead of "slice"

My code should place a banner after x number of words. The code works, but not as it should, since it uses slice for counting or slicing. I need to use (count >= 20) instead of slice(0, 20)

Thus, the words in the text will be counted, instead, the lines are calculated. This is the code that does what I need: https://jsfiddle.net/714Lmgfu/3/ However, this code has a loop that replicates the image (as shown in the script), and I could not do the work return false .

So, I got some help, and this was the final result https://jsfiddle.net/scadp0ar/ , this code works as it should, except that, as stated earlier, it does not take words into account. What should I change to count words instead?

For example, change:

  var img = '<img src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />' $(".newsitem_text").html(function (i, h) { return h.replace(h.split(/\s+/).slice(0, 20).join(' '), function (m) { return m + img; }); }); 

for

 function check() { if (count >= 20) { newHtml += '<img src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />' count = 0; } } 
0
source share
4 answers
 var img = '<img src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />' $(".newsitem_text").html(function (i, h) { // Match a word followed by one or more spaces 20 times // Insert <img>-tag // Repeat return h.replace(/([^\s]+\s+){20}/g, function (m) { return m + img; }); }); 

Structure:

 / # Start regex ( # Start capturing group [^\s]+ # Match everything - but space - 1 or more times # could also be written as .+? that means: # match everything 1 or more times, but not gready (meaning that if a space is encountered it will stop matching) \s+ # Match space 1 or more times ) # End group {20} # repeat 20 times / # End regex g # global flag - will run the regex multiply times until no more matches are posible 
+2
source

Try using String.prototype.match() with RegExp /\w+./g to match an alphanumeric character followed by any one character, Array.prototype.splice()

 var img = '<img src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />' var text = document.querySelector(".newsitem_text"); var html = text.innerHTML, matches = html.match(/\w+./g); matches.splice(20, 0, img); text.innerHTML = matches.join(" "); 
 <div style="width:450px; margin-left:auto; margin-right:auto" class="newsitem_text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec pellentesque urna eu pulvinar maximus. Sed elit nunc, vestibulum ut eros vitae, pellentesque rhoncus ipsum. In et metus non diam porttitor maximus iaculis nec lectus. Quisque sodales scelerisque auctor. Nam rutrum venenatis eros, eu condimentum erat placerat ut. Pellentesque sed tempus sem, eu viverra ipsum. Vestibulum nec turpis convallis, dapibus massa vitae, posuere mauris. Suspendisse mattis tincidunt lorem. Aliquam erat volutpat. Nullam at tincidunt erat, maximus laoreet ipsum. Quisque nunc neque, semper tincidunt placerat eget, blandit a ante. Suspendisse pulvinar, velit eu ultrices pulvinar, lacus sapien tincidunt ipsum, eget sollicitudin mauris eros molestie ex. Etiam quis orci dui. Phasellus vestibulum mollis molestie. Nam condimentum ornare nisl, sed finibus risus tempus vel. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Interdum et malesuada fames ac ante ipsum primis in faucibus. Vestibulum eget ullamcorper lorem. Aliquam mollis elit in sem dapibus dapibus. Proin vel massa a arcu dictum tincidunt in ut ante. Sed feugiat tempus dictum. Praesent in leo ullamcorper, sodales turpis et, vehicula tellus. Duis pellentesque dui ac turpis tristique imperdiet. Sed sed orci lectus. Suspendisse non egestas sem, sed tincidunt sem. Etiam laoreet dui sem. Mauris hendrerit massa tempus, euismod arcu sit amet, eleifend quam. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Phasellus id fringilla mauris. Cras dapibus non lacus at finibus. Nullam vitae sagittis neque. Mauris libero velit, interdum non vehicula non, lacinia non augue. Maecenas elementum lacinia interdum. Morbi eget mollis nisl. Integer accumsan condimentum tellus, lacinia pellentesque urna volutpat a. Nullam semper sem et erat commodo sollicitudin. Proin rhoncus felis eu aliquam venenatis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nulla pretium velit eu molestie condimentum. Vestibulum vitae velit mi. Integer nec leo quam. Nam pulvinar ligula congue consectetur tristique. Donec placerat faucibus diam sit amet fermentum. Ut id pellentesque risus. Nunc lacus orci, rhoncus ut risus sed, mattis posuere tellus. Nulla pellentesque eros sed neque consectetur dictum.</div> 

jsfiddle https://jsfiddle.net/scadp0ar/3/

+1
source

You should try something like this:

  var img = '<img src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />'; jQuery( document ).ready(function( $ ) { $(".newsitem_text").html(getTextWithImageBetweenWords($(".newsitem_text").html(),20)); }); function getTextWithImageBetweenWords(text, count){ var split_text = text.split(' '); var _out = []; var words = split_text.length; for(var i=0;i < words; i++){ if(i !== 0 && i === count){ _out[i] = split_text[i] + img; } else{ _out[i] = split_text[i]; } } return _out.join(' '); } 

This is a more readable and easier way to accomplish this, here is JSFiddle!

Note. If you want to repeat the image every n (20 in your case) words, just change i === count to i % count === 0 .

0
source

From your comment, you can edit the question (just for clarity, without trying to be a jerk). In addition, splitting in space, counting has words. '\ s' is a space '\ n' - a new line '\ t' - carriage return, '\ r \ n' - a special type of carriage return. You could create a more complex regular expression to cover anything that is not a newline or space '\ t \\ s \ r \ n'. To put an image in a line, you can use a style trick, as described below.

If you want the image not to repeat, change:

 function check() { if (count >= 20) { newHtml += '<img src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />' count = 0; } } 

For even better matching, try align = "right", which wraps text around the image.

 //jQuery(function ($) { jQuery( document ).ready(function( $ ) { var img = '<img align="right" src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />' $(".newsitem_text").html(function (i, h) { return h.replace(h.split(/\s+/).slice(20,21).join(' '), function (m) { return m + img; }); }); }); 

to

 function check() { if (count == 20) { newHtml += '<img src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />'; } } 

To avoid using an unpleasant loop, you can chop it in another place or use a splice:

 //jQuery(function ($) { jQuery( document ).ready(function( $ ) { var img = '<img src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />' $(".newsitem_text").html(function (i, h) { return h.replace(h.split(/\s+/).slice(20, 21).join(' '), function (m) { return m + img; }); }); }); 

To wrap your image in words, use align = "left" or align = "right" in the image tag.

 <img align="right" src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" /> 
0
source

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


All Articles