Skip to content

Instantly share code, notes, and snippets.

@dmitrizzle
Last active January 24, 2018 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmitrizzle/0d6916b8909737af89e5f88b8e34584e to your computer and use it in GitHub Desktop.
Save dmitrizzle/0d6916b8909737af89e5f88b8e34584e to your computer and use it in GitHub Desktop.
Trim string by total number of characters, but round to nearest sentence (ceiling)
const trimByCharToSentence = (text = "", chars = 0) => {
// string is broken down into sentences;
// this is done by splitting it into array between
// the most common sentence-ending punctuation marks:
// period, exclaimation, ellipsis and question mark;
// if string consists of a single statement, make an array
// anyways
const sentences = text.match(/[^\.!…\?]+[\.!…\?]+/g) || [text]
// store
let result = ""
// cycle through sentences array
sentences.forEach(sentence => {
// if the `result` store isn't long enough
// add a sentence, until we're out of available
// sentences
if(result.length < chars) result += sentence
})
// return the trimmed sentence or empty string as default
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment