# Basic Algorithm Scripting - Truncate a String

Tell us what’s happening:
Describe your issue in detail here.

``````function truncateString(str, num) {
let str1 = "";
for (let i = 0; i < num; i++) {
str1 += str[i];
}
return str1 += "...";
}

``````

User Agent is: `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36 Edg/117.0.2045.43`

Challenge: Basic Algorithm Scripting - Truncate a String

Learning to describe problems is hard, but it is an important part of learning how to code.

Also, the more you say, the more we can help!

1 Like

create blank string
iterate through str and copy until the character limit is reached

Yes…?

That appears to be a description of your code.

What’s wrong? What have go tried to fix it?

1 Like

got one part of it that was do not add … if string is not truncated however i get undefined when num is greater than the string length

So maybe you need some more complex logic to say how much of the string to copy

1 Like

found it break out the loop when the str[i] is undefined thanks

There’s probably a better solution. Why not find a better stopping condition initially before you loop?

1 Like

should i do a global capture with regular expressions to filter out the space but will that take out the undefined parts of the array?

You definitely do not need any regular expressions here

1 Like

how would it be done then

Right now you are looping through the string regardless of its size.

For example, consider this function call

``````truncateString("A-", 8);
``````

The string only has two characters in it.
Since 2 is less then 8, there is no need to truncate the string and in this case I would just return `"A-"`
In this case, there would be no need for a loop at all because you would just return the string.

A way to optimize your code is to first check the length of the string and then compare that length with the num parameter

By adding a condition first before the loop, then you are ensuring that you are only looping and truncating the string if it is in fact longer then the num input

Hope that helps

2 Likes

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