Basic Algorithm Scripting - Truncate a String

At least my code works as long as the number <= string.length.
For exceeding numbers (num > string.length) the console shows the string + undefined.
So… what can i do ?
Have seen the given solutions of this exercise , but i have to follow my own thoughts.

function truncateString(str, num) {
  let newStatement = "";
  for (let i=0; i<=num; i++) {
    if (i!==num) {newStatement+=str[i]}
    else (newStatement+="...");
    console.log(newStatement)}
  return newStatement;
}

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/110.0.0.0 Safari/537.36

Challenge: Basic Algorithm Scripting - Truncate a String

Link to the challenge:

so you made a loop to handle the case when the num is <= str.length which is great.
Now you just need to add some code to _____ the loop and do something else in the case num > str.length.

My hint is to do with ‘conditionals’.

Thank you (:

function truncateString(str, num) {
  let newStatement = "";
  for (let i=0; i<=num; i++) {
    if (i!==num) {newStatement+=str[i]}
    else (newStatement+="...");
    console.log(newStatement)} 
  console.log(str)
  return num>=str.length ? str : newStatement;
}

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

Can’t compare this construction with those beautiful codes in the soutions, but it works anyway

my 2 cents, could you have done the conditional earlier in order to “skip” the loop (that’s the blanked out word I had in my previous response).

We have blurred this solution (with [spoiler][/spoiler] tags) so that users who have not completed this challenge can read the discussion in this thread without giving away the solution.

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