From 8a4426c12926cff35cab3f6b6f83dde4956a9ac4 Mon Sep 17 00:00:00 2001 From: Alex Howes Date: Wed, 14 Oct 2020 20:10:01 +0100 Subject: [PATCH] Add truncateAtSpace --- snippets/truncateAtSpace.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 snippets/truncateAtSpace.md diff --git a/snippets/truncateAtSpace.md b/snippets/truncateAtSpace.md new file mode 100644 index 000000000..bd83c7539 --- /dev/null +++ b/snippets/truncateAtSpace.md @@ -0,0 +1,21 @@ +--- +title: truncateAtSpace +tags: string,beginner +--- + +Truncates a string up to the nearest space before a specified length. + +- Checks if there string can be truncated +- Calculates the nearest space before or at the strings set limit. +- Appends a configurable ending (defaulting to `'...'`) to the truncated string. + +```js +const truncateAtSpace = (string, characterLimit, ending = '...') => { + const lastSpace = string.slice(0, characterLimit + 1).lastIndexOf(' '); + return (string.length <= characterLimit) ? string : (lastSpace > 0) ? string.slice(0, lastSpace) + ending : ending; +} +``` + +```js +truncateAtSpace('This is a long excerpt that is far too long.', 25, '...'); // This is a long excerpt... +```