Truncate a string , weird result

I’m curious why this solution doesn’t work. I tried using indexOf to return the index of the argument position( num) but it returns some strange results. try changing the number arg to 10 or 11 or 12… why is the substring inconsistently returning different lengths?

function truncateString(str, num) {
  // Clear out that junk in your trunk
  return (str.length > num) ? str.substring(0,  str.indexOf(str[num])).concat('...'): str ;
  truncateString("A-tisket a-tasket A, green and yellow basket", 8))

You are using indexOf - I’m not sure why.

According to the test suite, you are failing for:

truncateString("Peter Piper picked a peck of pickled peppers", 11)

You are expected to return:

“Peter Piper…”

but you return


The math makes sense. The char at the point is a space, the second one in the string. And indexOf returns the first occurrence, which happens to be the first space. Why are you using indexOf - you already know the index where you need to truncate it.

so initially i didn’t understand the substring method and was trying to index the argument value where to capture the substring. later i realized i could just pass the argument directly.

i’m still not sure why it behaves the way it does though.

it actually works if there isn’t a space at the argument index. It passes all other tests except Peter Piper.

Console.log out he values and observe what is happening with different strings. Again, you don’t need indexOf.