javascripthtmlcssdynamic-text

How can I insert Html tags into incoming dynamic text


I have some incoming text from a database that's generated dynamically and it is being placed into a div, I'll call it:

<div id="dynamicText"> ${dataBase.text} </div>

What I want to do is dynamically place p tags inside of the database.text based on the number of complete sentences. So for example before the first line in database.text we have a starting p tag, then after the 8th completed sentence we have an ending p tag. Then repeat for every 8 sentences.

This is the expression I'm using to count the number of occurring sentences:

/\w[.?!](\s|$)/g

Ultimately here is the simplified code I have so far within an ajax request:

/* The reg expression for counting sentences */

 let re;
 re = /\w[.?!](\s|$)/g

const dataBase = JSON.parse(this.responseText);

/* Pull the text out the database object for counting sentences */
const dataBaseString = dataBase.text;


/* Count the number of senteces */
let count = (dataBaseString.match(re) || []).length;


const output = ` 
   <div class="ajaxText">
      ${dataBase.text }
   </div>
`;


document.getElementById('dynamicText').innerHTML = output;


I have no problems counting the sentences, the roadblock I'm running into is putting the p tags into the incoming text. I tried using insertAdjacentHTML() but I get an Uncaught TypeError: Cannot read property 'insertAdjacentHTML' of null error.

Any ideas on how this can be done, or if this can be done?


Solution

  • Voila!

    Based on responses from: Split string into sentences in javascript and Split array into chunks

    I have created a solution that I believe is a viable one. I am splitting the whole string ( database.text ) into and array of phrazes, than I create the chunks of 8 of phrazes, and in the end I append them to the wrapper.

    const wrapper = document.querySelector('.wrapper')
    
    const text = `... your stringified content`
    
    const array = text.replace(/([.?!])\s*(?=[A-Z])/g, "$1|").split("|")
    
    function chunker(array, chunkSize) {
      console.log(array)
      return [].concat.apply([],
        array.map(function(el, i) {
          return i % chunkSize ? [] : [array.slice(i, i + chunkSize)];
        })
      );
    }
    
    const paragraphs = chunker(array, 8)
    
    paragraphs.forEach((el) => {
        const p = document.createElement('p')
      p.innerText = el
      wrapper.append(p)
    })
    

    here is a JSfiddle I have prepared for you: https://jsfiddle.net/mkbctrlll/d5r38whL/35/