Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

146
Views
Split a string whilst keeping punctuation

I have a text with roughly 1500 - 2000 characters. This text should be split into blocks of text with roughly 400 characters each (does not have to be exactly 400 characters). However it should not just split the text every 400 characters, but split the text only at places where there is a full-stop. So basically divide one big text into several chunks without destroying punctuation.

Any Idea?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

We can try a reduce

I do 500 here since your text was < 400

let str = `I have a text with roughly 1500 - 2000 characters. This text should be split into blocks of text with roughly 400 characters each (does not have to be exactly 400 characters). However it should not just split the text every 400 characters, but split the text only at places where there is a full-stop. So basically divide one big text into several chunks without destroying punctuation. I have a text with roughly 1500 - 2000 characters. This text should be split into blocks of text with roughly 400 characters each (does not have to be exactly 400 characters). However it should not just split the text every 400 characters, but split the text only at places where there is a full-stop. So basically divide one big text into several chunks without destroying punctuation. I have a text with roughly 1500 - 2000 characters. This text should be split into blocks of text with roughly 400 characters each (does not have to be exactly 400 characters). However it should not just split the text every 400 characters, but split the text only at places where there is a full-stop. So basically divide one big text into several chunks without destroying punctuation.`

let nextPunct = str.indexOf(".")
const lines = str.split(/\.\s+/)
  .reduce((acc, line, i) => {
    if (i === 0) acc.push(line)
    else if ((acc[acc.length - 1].length + line.length) > 500) acc.push(line)
    else acc[acc.length - 1] += ". " + line;
    return acc
  }, [])
const res = lines.join(".\n")

console.log(res, lines.map(line => line.length))

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!