Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
76
rated 0 times [  78] [ 2]  / answers: 1 / hits: 15187  / 8 Years ago, mon, april 18, 2016, 12:00:00

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?


More From » string

 Answers
38

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

}

[#62498] Saturday, April 16, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
margaritakristinak

Total Points: 502
Total Questions: 127
Total Answers: 98

Location: England
Member since Mon, May 17, 2021
3 Years ago
;