Created
June 19, 2019 18:54
-
-
Save elmariachi111/f9bf3b1c19ea93a76a2ab6520baf38db to your computer and use it in GitHub Desktop.
Javascript: truncate a text along punctuation marks
This file contains 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
/* | |
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