Update 2 : Many guys post shorter and correct answer in here : Truncate string - understanding why this works
but the Answer page is not changed yet, Why ?
Update 1 : the codes in solution page are wrong !!!
Tell us what’s happening:
It’s seem my code is shorter than the answer, Am I wrong ?
And If I right, where to contribute this ?
Thanks,
##Requirement:
truncateString("A-tisket a-tasket A green and yellow basket", 8)
should return “A-tisket…”.
truncateString("Peter Piper picked a peck of pickled peppers", 11)
should return “Peter Piper…”.
truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length)
should return “A-tisket a-tasket A green and yellow basket”.
truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length + 2)
should return “A-tisket a-tasket A green and yellow basket”.
truncateString("A-", 1)
should return “A…”.
truncateString("Absolutely Longer", 2)
should return “Ab…”.
My code so far
##Result
Here is the answer on Help page :
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;
}
}
Advanced Code Solution:
function truncateString(str, num) {
if (str.length <= num) {
return str;
} else {
return str.slice(0, num > 3 ? num - 3 : num) + '...';
}
}
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36
.
Link to the challenge: