Basic Algorithm Scripting - Truncate a String

Tell us what’s happening:
Describe your issue in detail here.

Your code so far
I have used the slice method, but I don’t understand why the splice method is not working since it is used to remove or/and items to an existing array.

function truncateString(str, num) {
  let newStr = str.split('');
  return (newStr.length > num) ? newStr.splice(0, num, '...').join('') : str;

console.log(truncateString("A-tisket a-tasket A green and yellow basket", 8));

Your browser information:

User Agent is: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/113.0

Challenge: Basic Algorithm Scripting - Truncate a String

Link to the challenge:

The output of the program is ‘A-ticket’.

The instruction says : Return the truncated string with a ... ending.
You should return something like this :


Happy coding. :grinning:

Yeah, I know. The splice method is use to remove or/and replace items so I think my code should work.

newStr.splice(0, num, '...')

It returns an array of items removed from index 0 to num.
It adds the ‘…’ to the original array, NOT into those removed items above, which is the part you missing.

A-tisket   // returning
... a-tasket A green and yellow basket // newStr

About splice, you can read more here >>> JavaScript Array splice() Method

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.