4.8 KiB
title
| title |
|---|
| Truncate a String |
Remember to use Read-Search-Ask if you get stuck. Try to pair program
and write your own code 
Problem Explanation:
We need to reduce the length of the string or truncate it if it is longer than the given maximum length specified and add ... to the end. If it is not that long then we keep it as is.
Relevant Links
Hint: 1
Strings are immutable in JavaScript so we will need a new variable to store the truncated string.
try to solve the problem now
Hint: 2
You will need to use the slice() method and specify where to start and where to stop.
try to solve the problem now
Spoiler Alert!
Solution ahead!
Basic Code Solution:
function truncateString(str, num) {
// Clear out that junk in your trunk
if(str.length > num) {
return str.slice(0,num)+"...";
} else {
return str;
}
}
Code Explanation:
- We start off with a simple
ifstatement to determine one of two outcomes... - If our string length is greater than the
numwe want to truncate it, we return a slice of our string starting at character 0, and ending atnum. We then append our'...'to the end of the string. - However, if above situation is not true, it means our string length is less than our truncation
num. Therefore, we can just return the string.
Advanced Code Solution:
function truncateString(str, num) {
return (str.length > num)?(str.slice(0,num)+"..."):str;
}
Code Explanation:
-
This solution is very similar to basic solution. To determine the new string, we use a ternary operator. In our ternary operation, if
str.lengthis larger thannum, we return a new string which is slice of our string starting at character 0, and ending atnumand the'...'is appended to the end of our new string. Ifstr.lengthis less than or equal tonum, we return the string without any truncation. -
NOTE In order to understand the above code, you need to understand how a Ternary Operator works. The Ternary Operator is frequently used as a shortcut for the
ifstatement and follows this format:condition ? expr1 : expr2. If theconditionevaluates to true, the operator returns the value ofexpr1. Otherwise, it returns the value ofexpr2.




