freeCodeCamp Algorithm Challenge Guide: Truncate a String

freeCodeCamp Algorithm Challenge Guide: Truncate a String
0

#1

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 lengths specified and add `...` to the end. If it is not that long then we keep it as is.

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

Hint: 3

Do not forget that when we truncate the word, we also must count the length added by `...`

try to solve the problem now

Basic Code Solution:

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

}
``````

Code Explanation:

• First we start off with a simple `if` statement to determine one of three outcomes…
1. 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.
2. 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`.
3. 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) {
if (str.length > num)
return str.slice(0, num > 3 ? num-3 : num) + '...';
return str;
}
``````

Code Explanation:

• We start by writing an if-statement that checks if the length of the string in the first argument is greater than the size limit. If so we need to use the “slice” method to extract a section of the string and return it as a new string. Here we pass 0 as the starting point for our slice. To determine the endpoint, we use a ternary operator: `num > 3 ? num - 3 : num`. In our ternary, if `num` is larger than 3, we must factor in the three dots to our total length, and thus we end our slice at `num-3`. If num is less than or equal to 3, our slice gets an end variable of just `num`. Finally, the `'...'` is appended to the end of our new string and is returned.function.
``````if (str.length > num)
return str.slice(0, num > 3 ? num-3 : num) + '...';
``````
• If our `if` statement above fails, the program will skip over it including the return statement. In this case we are able to skip a follow-up “else” statement and return the original string.
``````return str;
``````
• 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`.

NOTES FOR CONTRIBUTIONS:

• DO NOT add solutions that are similar to any existing solutions. If you think it is similar but better, then try to merge (or replace) the existing similar solution.
• Categorize the solution in one of the following categories — Basic, Intermediate and Advanced.

See `Wiki Challenge Solution Template` for reference.

Someone with the good eyes ? I don't see the difference in my code and Hint code, but Hint works and my not
Truncate a String (regarding the number 3)
Truncate a String wrong something in my code
#2

#3

#5

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…

#6

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);
``````

#7

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) + "...";
}

``````

#8
``````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

#9

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.

#10

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);
}
}``````

#12
``````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;
}``````

#13

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;
}

``````

#14

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;
}``````

#16

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);``````

#17

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;
}

#18

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(’’)+"…";
}
}

#19

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;

#20

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) + "...");
}``````

#21

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;
}
}``````

#22

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;
}

#23

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);