Marc Freeman Marc Freeman - 5 months ago 19
Javascript Question

Truncate a string JavaScript

My task is to "truncate a string (first argument), if it is longer than the given maximum string length (second argument). Return the truncated string with a ... ending.

Note that inserting the three dots to the end will add to the string length.

However, if the given maximum string length num is less than or equal to 3, then the addition of the three dots does not add to the string length in determining the truncated string."

I have written the code:

function truncateString(str, num) {
if (num > str.length){
str.slice(num);
return str.append("...");
}
else if (num < 3) {
str.slice(3);
return str.append("...");
}
else {
return "This is not a string";
}

}

truncateString("A-tisket a-tasket A green and yellow basket", 11);


However, it's not doing what I need it to do and returns "This is not a string" on every run. Can anyone help me?

Answer

And "This is not a string" is the correct answer, why should it be?

function truncateString(str, num) {
  if (num > str.length){ // if num is greater than string length (in you case 11 is not greater than 43
    str.slice(num);
    return str.append("...");
  } 
  else if (num < 3) {   // or if the num is less than 3 (11 is not less than 3)
    str.slice(3);
    return str.append("...");
  }
  else { // do if no if was matched (and here we are)
    return "This is not a string";
  }

}

So basically what you need is to change > to < in your first if :)

Edit:

The final code you want to have is (str.append() is not a function):

function truncateString(str, num) {
  if (num < str.length){
    str.slice(num);
    return str + "...";
  } 
  else if (num < 3) {
    str.slice(3);
    return str + "...";
  }
  else {
    return "This is not a string";
  }

}