Tell us what’s happening:
I don’t want to look at to solution, I need someone who can give me a hint. I want to truncate these string, if the length of the string is more than num.
I wrote a ‘solution’ and it didn’t work, I don’t know why. I creat a new array (let arr = [ ];).
I check if the length of the string is more than num (if (str.length > num) ).
Then I creat a variable result equals to the result of the array that slice method will give ( let result = str.slice(0, num);).
I use the spread method to copy the result and input it in my empty array that I created at the begining (arr = […result];).
the instruction tells me that the truncated string should have (…) ending. I push it(…) in my arr array(return arr.push(’…’);). else I return str .
What’s the problem with this solution ?
**Your code so far**
function truncateString(str, num) {
let arr = [];
if (str.length > num) {
let result = str.slice(0, num);
arr = [...result];
return arr.push('...');
}
return str;
}
truncateString("A-tisket a-tasket A green and yellow basket", 8);
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36.
function truncateString(str, num) {
let arr = [];
if (str.length > num) {
let result = str.slice(0, num);
arr = [...result];
console.log(arr);
return arr.push('...');
}
return str;
}
truncateString("A-tisket a-tasket A green and yellow basket", 8);
This is an important clue. You have an array. It looks like you took apart the string and put in into an array. The function output needs to be all joined back up again. Is there some JavaScript function that can help you do that?
I know what you mean. But I am a little bit confused. My code is almost correct and I have to add something ? I know the join method (.join) could do something like that.