Truncate a string different method

Tell us what’s happening:

I understand after reading ask for a hint that this might not be the most efficient way to write this code but I was trying to go as far as i could without looking. does anyone know if can be solved this type of way/where I’m going wrong?

Your code so far


function truncateString(str, num) {

var splitstr = str.split('')
var newstring = ''

for(var i = 0; i < num; i++) 
if (str.length > num){
newstring = splitstr[i].concat;
}

if (str.length < num) { return str
}

return newstring + '...'
}
console.log(newstring)

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



Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36.

Challenge: Truncate a String

Link to the challenge:

it can work, just a few things to consider:

there is no need to enter in the loop if str.length > num is false, but if it is you still loop throgh the whole string

the use for the loop is to loop through all of the split-string array to append a new string with the number of iterations that is provided by num.

function truncateString(str, num) {

var splitstr = str.split('')
var newstring = ''

for(var i = 0; i < num; i++) 
if (str.length > num){
  newstring = splitstr[i].concat;
  }

  return newstring + '...'
}

is this a little closer?

can you show me where is the open and close brackets of for loop?

now I don’t think ti passes anymore. what about when num is higher than the string length? as it is it just returns ...


I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

1 Like

I did not notice before, but what should that do?

1 Like

the loop works like that too, it consider the next line/expression to be inside the loop

1 Like

yes. so

 if (str.length > num){
newstring=splitstr[i].concat;
}

is executed in for loop.

newstring = splitstr[i].concat; // Wrong syntax. 

correct syntax of ‘concat’ method.