Skip to content

Instantly share code, notes, and snippets.

@elmariachi111
Created June 19, 2019 18:54
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 elmariachi111/f9bf3b1c19ea93a76a2ab6520baf38db to your computer and use it in GitHub Desktop.
Save elmariachi111/f9bf3b1c19ea93a76a2ab6520baf38db to your computer and use it in GitHub Desktop.
Javascript: truncate a text along punctuation marks
/*
assume you want to truncate a longer text to a certain amount of characters but you don't want to stop at
word boundaries. Instead lets cut the text at sentence ending punctuation marks like ! ? .
*/
function pos(str, char) {
let pos = 0
const ret = []
while ( (pos = str.indexOf(char, pos + 1)) != -1) {
ret.push(pos)
}
return ret
}
function truncate(str, len) {
if (str.length < len)
return str
const allPos = [ ...pos(str, '!'), ...pos(str, '.'), ...pos(str, '?')].sort( (a,b) => a-b )
if (allPos.length === 0) {
return str.substr(0, len)
}
for(let i = 0; i < allPos.length; i++) {
if (allPos[i] > len) {
return str.substr(0, allPos[i-1] + 1)
}
}
}
module.exports = truncate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment