In this challenge its required to truncate a string (first argument) if it is longer than the given maximum string length (second argument). Then return the truncated string with a "..." ending.
Note that the three dots at the end add to the string length.
If the
num
is less than or equal to 3, then the length of the three dots is not added to the string length.
The given clue here is :
The
slice()
method extracts a section of a string and returns a new string.
The syntax is as follows;
str.slice(beginSlice[, endSlice])
beginSlice
- The zero-based index at which to begin extraction.
endSlice
- Optional. The zero-based index at which to end extraction.
It was not that hard to implement the solution.
My solution is as follows:
function truncate(str, num) {
var x = str.slice(0, num);
if (num <= 3){
return x+"...";
} else if (str.length <= num){
return x;
} else {
return x.slice(0, num-3)+"...";
}
}
No comments:
Post a Comment