0

My code is supposed to place a banner after x amount of words. The code is working, but not as it should, as it is using slice to make the counting or slicing. I need to use (count >= 20) instead of slice(0, 20)

This way the words in the text will be counted, instead counting the lines. This is the code that does what I need: https://jsfiddle.net/714Lmgfu/3/ However, there is a loop in this code, which replicates the image (As show in the Fiddle) and I was not able to make return false working.

So I got some help and this was the final result https://jsfiddle.net/scadp0ar/, this code is working the way it should, except that, as stated before, it doesn't count the words. What should I change to make it count the 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;
    }
  }
Matheus Lopes
  • 315
  • 3
  • 14
  • For insertion of something in mid-array, I'm guessing you should be using [.splice()](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/splice), not [.slice()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice). – Roamer-1888 Nov 05 '15 at 23:00
  • Also, to stop the repeating just set count == 20 and remove count = 0 – Andrew Scott Evans Nov 05 '15 at 23:01
  • @Andrew, can you post it as a reply? I'll mark it as the best answer. – Matheus Lopes Nov 05 '15 at 23:08
  • I didn't think this is what you wanted. Maybe change the question to something closer to how to stop an image from repeating or how to splice an array at a specific index given node contents. – Andrew Scott Evans Nov 05 '15 at 23:25
  • Is [this](https://jsfiddle.net/oe51r86L/) what you want? – Roamer-1888 Nov 05 '15 at 23:41

4 Answers4

2
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;
    });
});

Breakdown:

/ # 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
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
1

Try using String.prototype.match() with RegExp /\w+./g to match alphanumeric character followed by any single 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/

guest271314
  • 1
  • 15
  • 104
  • 177
0

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 easy way to accomplish this, here is the JSFiddle!

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

Winner Crespo
  • 1,644
  • 15
  • 29
0

From your comment, you may want to edit the question (just for clarity not trying to be a jerk). Also, by splitting at space, the count is of words. '\s' is space '\n' is new line '\t' is carriage return, '\r\n' is a special type of carriage return. You could potentially make a more complicated regex to cover everything that is not a new line or a space '\t|\s|\r\n'. To place the image within lines, you can use a styling trick as explained later.

If you want to have the image not 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 an even nicer fit, try align="right" which will wrap the 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 a nasty loop, you could slice at a different location or use 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 within the 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" />
Andrew Scott Evans
  • 1,003
  • 12
  • 26
  • I am also looking into a way to stop looping through the entire script in your code as a fun break at work. May or may not get done but I will update with findings. – Andrew Scott Evans Nov 05 '15 at 23:23