Truncate a String - Is my code imaginable possible if coded correctly?

So, is my following code on the rigth path and am i atleast thinking right in order to get it solutionable working.

function truncateString(str, num) {
  // Clear out that junk in your trunk
  var array = [];
  var dots = "...";
  
  for (i = 0; i < str.length; i++) {
    if (str.length > num && str[i] === num) {
      array = str[i];
    }
  }
  
  var joinedStr = array.push(dots).join("");
  
  return joinedStr;
}

truncateString("A-tisket a-tasket A green and yellow basket", 11);

Have you run this code to check for any error messages?

A couple of things:

Why are you making this comparison?
str[i] === num
str[i] is a character in the string and num is a number.

Why do you assign a character to your array variable?
array = str[i];
push() and join() will not work on a character.

The error message that shows up is: TypeError: array.push(…).join("") is not a function.

As i have had no explanation on the topic as to what [i] meant i assumed it was the length at which the for loop was stopped. So for example i thought the output str[i] would have meant to be “A-tisket a-” which has length 11.

So figuring your questions i assume str[i], following my code, is only 1 character and to be exact is the twelfth?

Answering your questions plainly; "Why am i making the str[i] === num comparison. I thought the comparison , lower then would stop @ a given point when the if statement would define true. Giving [i] the first, until the last, string as a output. Following the idea of having str[i] === “A-tisket a-” with str[i] also saving the length. I basically thought the for loop would return a string.

For example, if str is “A-tisket”, str[0] is “A”, str[1] is “-”, etc. I think str[i] is another way of writing str.charAt(i). I don’t think this is what you want.

You can read an explanation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charAt

I think your thinking is on the right track, but you’re not using the right functions to get the output that you are expecting. Did you read the link provided on the challenge page about the slice function?

I always do the first thing that comes to my mind when i am doing a exercise. This time it was a more complicated approach in my thinking to the solution.

I understand splice and figured it out by following the hints provided on the forum. As i saw the solution, i was perplexed as to how simple it was.

Thanks for putting a interest into my post, makes me feel satisfied about the exersice.

It’s great that you figured it out. It can be useful to think of the complicated approach, especially if you end up trying to learn other programming languages that don’t provide convenient string functions like slice :slight_smile:.