Skip to content

Instantly share code, notes, and snippets.

@paulohfev
Last active July 1, 2022 02:59
Show Gist options
  • Save paulohfev/94022ef5932cc713a386fe53349aaa9e to your computer and use it in GitHub Desktop.
Save paulohfev/94022ef5932cc713a386fe53349aaa9e to your computer and use it in GitHub Desktop.
Create a content excerpt
const createContentExcerpt = (content, maxNumberOfWords, trailingIndicator = '...') => {
const listOfWords = content.trim().split(' ');
const truncatedContent = listOfWords.slice(0, maxNumberOfWords).join(' ');
const excerpt = truncatedContent + trailingIndicator;
const result = listOfWords.length > maxNumberOfWords ? excerpt : content;
return result;
};
// Example:
// createContentExcerpt('Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 3);
// Result: Lorem ipsum dolor...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment