From 3676d11b0c8b2fd3f104a38ab1dae58a296cac0c Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Wed, 13 Dec 2017 13:44:38 +0200 Subject: [PATCH] Update truncate_a_string.md Updated description and added example. --- snippets/truncate_a_string.md | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/snippets/truncate_a_string.md b/snippets/truncate_a_string.md index a3bc9321d..5c2a091cb 100644 --- a/snippets/truncate_a_string.md +++ b/snippets/truncate_a_string.md @@ -1,14 +1,10 @@ ### Truncate a String -First we start off with a simple if statement to determine one of three outcomes… -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. -However, if our string length is greater than the num but num is within the first three characters, we don’t 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. +Determine if the string's `length` is greater than `num`. +Return the string truncated to the desired length, with `...` appended to the end or the original string. ``` -function truncateString(str, num) { - if (str.length > num) - return str.slice(0, num > 3 ? num-3 : num) + '...'; - return str; -} +const truncate = (str, num) => + str.length > num ? str.slice(0, num > 3 ? num-3 : num) + '...' : str; +// truncate('boomerang', 7) -> 'boom...' ```