 # freeCodeCamp Challenge Guide: Truncate a String

freeCodeCamp Challenge Guide: Truncate a String
0

# Truncate a String

## 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.

## Hints

### Hint 1

Strings are immutable in JavaScript so we will need a new variable to store the truncated string.

### Hint 2

You will need to use the slice() method and specify where to start and where to stop.

## Solutions

Solution 1 (Click to Show/Hide)
``````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 `if` statement to determine one of two outcomes…
• If our string length is greater than the `num` we want to truncate it, we return a slice of our string starting at character 0, and ending at `num`. 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.
Solution 2 (Click to Show/Hide)
``````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.length` is larger than `num`, we return a new string which is slice of our string starting at character 0, and ending at `num` and the `'...'` is appended to the end of our new string. If `str.length` is less than or equal to `num`, 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 `if` statement and follows this format: `condition ? expr1 : expr2`. If the `condition` evaluates to true, the operator returns the value of `expr1`. Otherwise, it returns the value of `expr2`.

20 Likes

function truncateString(str, num) {

var opStr = function(str, num1){
var res = ‘’;
res = str.slice(0, num1) + ‘…’;
return res;
};

if (num > 3 && str.length > num ){

``````return opStr(str, num-3);
``````

}else if( num <= 3 && num > 0 && str.length > num) {

``````return opStr(str,num);
``````

}else{

``````return str;
``````

}

}

My code… it´s a beginners code…

2 Likes

Another Basic solution is here but using substr():

``````function truncateString(str, num) {
// Cleared out that junk in my trunk
var substring="";
if(num<=3)
{
substring=str.substr(0,num);
}
else{
substring=str.substr(0,num-3);
}
if(num>=str.length)
{
return str;
}
return substring.concat("...");
}

truncateString("A-",1);
``````
5 Likes

My Solution-

``````function truncateString(str, num) {
// Clear out that junk in your trunk
if(str.length<=num){
return str;
}

var strSliced = str.slice(0,num);

if(strSliced.length<=3){
return strSliced + "...";
}
return strSliced.slice(0,-3) + "...";
}

``````
``````function truncateString(str, num) {
if (num <= 3){
return str.slice(0, num) + "...";
}
else {
return num >= str.length ? str : str.slice(0, num - 3) + "...";
}
}
``````

This worked out pretty well for me Guys, this is coming from me as an individual but wouldn’t it be better to explain the code you guys posted otherwise whats the point of pasting your answers on this wiki post? You can always open your own thread to show your answer or ask for feedback.

I believe the point to these type of articles is to explain the problem and how to solve it with hints and code with explanations so others that are stuck can get some help and learn more.

32 Likes

I also went with an If else statement; the num smaller than 3 part seemed easy, but i struggled with that! Otherwise the ternary was useful to evaluate the required conditions. ``````function truncateString(str, num) {
if (num <= 3) {
return str.slice(0,num)+"...";
}
else {
return str.length > num ? str.slice(0,num-3)+"..." : str.slice(0,num);
}
}``````
1 Like
``````function truncateString(str, num) {

// If string length is greater than num -
// it should be truncated.
if (str.length > num) {

// And if num is greater than 3,
// remove that from the length.
if ( num > 3) num -= 3;

//Remove end of string from num and concatenate with "..."
str = str.substring(0, num).concat("...");
}

//Return the string. If it was not bigger than num -
//return the whole string.
return str;
}``````
8 Likes

My solution

``````function truncateString(str, num) {
// Clear out that junk in your trunk

//First: Set the length of the string
var lengthString=str.length;

// if length is less than 3
if (num <= 3) {
str = str.slice(0,num);
str = str.concat('...');
}

// if not do the slice thing :/
else if (lengthString > num) {
str =  str.slice(0, num-3);
str = str.concat('...');
}

return str;
}

``````
1 Like

i am still a little fuzzy on why the solution has 3 (representing the …) in it.
my solution works without the 3. is there some problem with mine I’m not seeing?

``````function truncateString(str, num) {
let a = str.length;
let b = str.slice(0,num);
return (a > num) ? b + "..." : str;
}``````
10 Likes

My code:
function truncateString(str, num) {

``````  if(num <= 3){
return str.substr(0, num) + "...";
}

if(str.length > num){
return str.substr(0, num-3) + "...";
}

return str;
}

//test
truncateString("A-", 1);``````
1 Like

I like the one line solution and using ternary operator

``````function truncateString(str, num) {
return str.length > num ? num >=3 ? str.slice(0, num - 3) + '...' : str.slice(0, num) + '...' : str;
}

2 Likes

function truncateString(str, num) {
// Clear out that junk in your trunk
var i=0;

var arr=[];
var lis=[];
if(num<3){
while(i<num){
arr.unshift(str[i]);
i++;
}
return arr.reverse().join(’’)+"…";
}
else if(str.length<=num){
return str;
}
else{
while(i<num-3){
arr.unshift(str[i]);

``````i++;
``````

}
return arr.reverse().join(’’)+"…";
}
}

function truncateString(str, num) {
var m; // Clear out that junk in your trunk
if (str.length<=num)
{

``````return str;
``````

}

else if (num < 3)
{

``````  m=str.slice(0,num);
m+="...";
return m ;
}
``````

else { m = str.slice(0,num-3);

m += “…”;

}
return m;

Here is my solution that just returns the truncated string without the need for extra variables.

``````function truncateString(str, num) {

return num <= 3 ? str.slice(0, num) + "..." : (str.length <= num ? str : str.slice(0, num - 3) + "...");
}``````

This thread taught me the Ternary Operator, very handy!
The solution I came up with is almost identical to the basic solution but with an added string-checker which excludes other objects in the input.

``````function truncateString(str, num) {
if (typeof str !== "string") {
return "Not a String!";
} else if (str.length > num && num <= 3) {
return str.slice(0, num) + "...";
} else if (str.length > num && num > 3) {
return str.slice(0, num - 3) + "...";
} else {
return str;
}
}``````
1 Like

this piece of code does produce the exact results as left side panel wants(all set conditions are met). i tried with all the conditions shown and it meets but still does not accept the challenge as solution. can anyone tell what can be the reason? THANKS for suggestions in advance.

function truncateString(str, num) {

var a=’’;
if (num>3&&num<str.length){
a=str.slice(0, num-3)+"…";
}
else if(num>3&&num>=str.length){
a=’"’+str+’"’+’.’;
}
else{
a=str.slice(0, num)+"…";
}
return a;
}

function truncateString(str, num) {
// Clear out that junk in your trunk
if(str.length===3){
return “…”;
} if(num<=2){
return str.slice(0, num) + “…”;
}if(num>=str.length){
return str;
}else {
return str.slice(0, num-3) + “…”;

}
}

truncateString(“A-”, 1);