"Truncate a String" - Where did we learn using slice() with strings?

I just solved “Truncate a String” by using a for loop, iterating through the characters of the string str and adding them to a new string trunStr, as long as they are not longer than the given length limit num. And if they are longer then also add the three dots:

My solution
function truncateString(str, num) {
  let trunStr = "";
  let adddots = 0;
  for (let i = 0; i < str.length; i++ ) {
    if (i < num) {
      trunStr = trunStr + str[i];
    } else {
      adddots = 1;
  if (adddots == 1) {
    trunStr = trunStr + "...";
    return trunStr;
  return trunStr;

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

Then i checked the solutions and the forum - nearly everbody is using the slice() method, but it only was introduced for copying arrays so far, not mentioning strings? Did I miss something? Or should I just have assumed it c/would work with strings also?

Algoritm scripting sections of the course allow you to solve problems using not only things that have been taught in previous parts of curriculum.
The assumption is that some learners do additional research/experimenting while going through exercises.
So don’t get too much concerned about many people using methods/approaches you’re not familiar with.
That said, I checked solutions for this step from guide. I definitely would like to see there the approach with using just for loops. It is totally fine to solve this kind of probs without slice or other array iterators.

Minor note: please consider to include the link to the relevant challenge step in your posts

1 Like

Ok, I see…, thank you for the kind words!

( Here is the link to the challenge: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/truncate-a-string )

you did a great job, you solved the algorithm! Don’t worry if others use methods you don’t, take it as a chance to learn things you don’t know yet!

1 Like