Update and rename truncateAtSpace.md to truncateStringAtWhitespace.md
This commit is contained in:
@ -1,21 +0,0 @@
|
|||||||
---
|
|
||||||
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...
|
|
||||||
```
|
|
||||||
26
snippets/truncateStringAtWhitespace.md
Normal file
26
snippets/truncateStringAtWhitespace.md
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
---
|
||||||
|
title: truncateStringAtWhitespace
|
||||||
|
tags: string,intermediate
|
||||||
|
---
|
||||||
|
|
||||||
|
Truncates a string up to specified length, respecting whitespace when possible.
|
||||||
|
|
||||||
|
- Determine if the string's `length` is greater or equal to `lim`. If not, return it as-is.
|
||||||
|
- Use `String.prototype.slice()` and `String.prototype.lastIndexOf()` to find the index of the last space below the desired `lim`.
|
||||||
|
- Use `String.prototype.slice()` to appropriately truncate `str` based on `lastSpace`, respecting whitespace if possible and appending `ending` at the end.
|
||||||
|
- Omit the third argument, `ending`, to use the default ending of `'...'`.
|
||||||
|
|
||||||
|
```js
|
||||||
|
const truncateStringAtWhitespace = (str, lim, ending = '...') => {
|
||||||
|
if (str.length <= lim) return str;
|
||||||
|
const lastSpace = str.slice(0, lim - ending.length + 1).lastIndexOf(' ');
|
||||||
|
return str.slice(0, lastSpace > 0 ? lastSpace : lim - ending.length) + ending;
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
truncateStringAtWhitespace('short', 10); // 'short'
|
||||||
|
truncateStringAtWhitespace('not so short', 10); // 'not so...'
|
||||||
|
truncateStringAtWhitespace('trying a thing', 10); // 'trying...'
|
||||||
|
truncateStringAtWhitespace('javascripting', 10); // 'javascr...'
|
||||||
|
```
|
||||||
Reference in New Issue
Block a user