Update truncate_a_string.md

Updated description and added example.
This commit is contained in:
Angelos Chalaris
2017-12-13 13:44:38 +02:00
committed by GitHub
parent e59fe392d1
commit 3676d11b0c

View File

@ -1,14 +1,10 @@
### Truncate a String ### Truncate a String
First we start off with a simple if statement to determine one of three outcomes… Determine if the string's `length` is greater than `num`.
If our string length is greater than the num we want to truncate at, and our truncate point is at least three characters or more into the string, we return a slice of our string starting at character 0, and ending at num - 3. We then append our '...' to the end of the string. Return the string truncated to the desired length, with `...` appended to the end or the original string.
However, if our string length is greater than the num but num is within the first three characters, we dont have to count our dots as characters. Therefore, we return the same string as above, with one difference: The endpoint of our slice is now just num.
Finally, if none of the above situations are true, it means our string length is less than our truncation num. Therefore, we can just return the string.
``` ```
function truncateString(str, num) { const truncate = (str, num) =>
if (str.length > num) str.length > num ? str.slice(0, num > 3 ? num-3 : num) + '...' : str;
return str.slice(0, num > 3 ? num-3 : num) + '...'; // truncate('boomerang', 7) -> 'boom...'
return str;
}
``` ```