1

I'm trying to split the string by word count, the below example is split by character count.

eg. I have 25 words of content.

var text = `Lorem ipsum dolor sit amet, consectetuer adipiscing elit. 
    Aenean commodo ligula eget dolor. 
    Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur.`


var part1 =  text.substr(0, text.substr(0, text.length > 100 ? 100 : text.length ).lastIndexOf(" "));

var part2 =  text.substr(text.substr(0, text.length > 100 ? 100 : text.length ).lastIndexOf(" "));

console.log(part1);
console.log(part2);

the output will be like this : part 1

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. 
Aenean commodo ligula eget dolor

part 2

Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur.

How to achieve the same output by word count, like 10 words in part 1 and remaining in part 2

note: The format of the content should print as it is.

1

2 Answers 2

1

Here is a way you can do it. I first split all the words by space (assuming that is how you want to split words). Once I have an array of words, I then iterate over all them and check the index to see if it belongs in part1 or part2. Finally, I return both parts in an array so that both can be extracted upon calling.

const splitWords = (text, numWords) => {
  const words = text.split(' ')
  let part1 = '', part2 = ''
  words.forEach((word, idx) => {
    if (idx < numWords) {
       part1 += ' ' + word
    } else {
        part2 += ' ' + word 
    }
  })
  return [part1.trim(), part2.trim()]
}

const [ part1, part2 ] = splitWords(text, 25)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, but the format of the content should be as it is, while print part1 and part2.
1

Here is another solution. Words splitted by spaces and spliced in the middle. Array is then joined back together with spaces.

    var text = `Lorem ipsum dolor sit amet, consectetuer adipiscing elit. 
Aenean commodo ligula eget dolor. 
Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur.`

    
    let part2=text.split(' ').filter(Boolean);
    let part1=part2.splice(0,(part2.length/2)+1).join(" ")
    part2=part2.join(" ")
    
    console.log(part1);
    console.log(part2);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.