Last active
January 24, 2018 16:46
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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