-
-
Save having-fun-coding/a401fd1d1ed7f8e97ca7 to your computer and use it in GitHub Desktop.
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 the three dots at the end add to the string length. | |
Here are some helpful links: | |
String.slice() |
function truncate(str, num) { | |
if (str.length > num) { | |
str = str.slice (0, num-3) + '...'; | |
} | |
return str; | |
} | |
truncate('A-tisket a-tasket A green and yellow basket', 11); |
function truncateString(str, num) {
if (str.length > num) {
if (num > 3 ) {
str = str.slice(0,num-3) + "...";
return str;
} else {
str = str.slice(0,num) + "...";
return str;
}
} else {
return str;
}
}
truncateString("A-", 1);
My solution using Conditional (ternary) Operator:
function truncateString(str, num) {
return str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str;
}
After a week of dirtying my code editor with this challenge, i later got it right . checkout below
function shortenStr (str, num){
if(str.length > num){ //checks if the length of the given string is greater than the specified number.
return str.slice( 0, num ) + "..." //if the condition above is true, the slice method will start from index [0] of str and stop in the specified number adding "..." as suffix.
} else {return str} // if the condition above is false, then it returns the initial string in the argument.
}
shortenStr("I will always code to improve my skills", 9)
//After a week of dirtying my code editor with this challenge, i later got it right . checkout below function shortenStr (str, num){ if(str.length > num){ //checks if the length of the given string is greater than the specified number. return str.slice( 0, num ) + "..." //if the condition above is true, the slice method will start from index [0] of str and stop in the specified number adding "..." as suffix. } else {return str} // if the condition above is false, then it returns the initial string in the argument. } shortenStr("I will always code to improve my skills", 9)
Solution 1:Basic(recommend)
Solution 2:Advanced