Home > Software design >  How to convert plain text into multiple paragraph text passing words count in Node js?
How to convert plain text into multiple paragraph text passing words count in Node js?

Time:10-03

I have a plain text having 5000 words and need to convert that plain text into multiple paragraphs with 1000 words as each paragraph.

Is there any possibility to achieve this, If yes pls help me with the answer.

CodePudding user response:

You can do it with .substring()

const text = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean m";

const paragraphLength = 50;

console.log(text.length);

for(let i = 0; i<text.length; i =paragraphLength){
  console.log(text.substring(i, i paragraphLength));
}

CodePudding user response:

break your words into list of word, then slice it into list with specific length and finally join the sublist to become string

let words = "your words here, just put in this variable"
let wordList = words.split(" ")
let maxWordsInSinglePar = 3
let maxPar = Math.ceil(wordList.length / maxWordsInSinglePar)
for (let i = 0; i < maxPar; i  ){
  let start = i * maxWordsInSinglePar
  let end = start   maxWordsInSinglePar
  if (end > wordList.length){
    end = wordList.length
  }
  console.log(wordList.slice(start, end).join(" "))
}

CodePudding user response:

const text = Array.from(Array(5000), (a, i) => `word${i}`).join(" ");
        var regexp = /[^\s] /g
        const res = [...text.matchAll(regexp)];
        var paragraphs = [];
        for (var i = 0; i < res.length; i  = 1000) {
            var paragraph = res.slice(i, Math.min(i   1000,text.length));
            paragraphs.push(paragraph.join(" "));
        }
        console.log("Response",paragraphs);

  • Related