Basic Algorithm Scripting: Truncate a String (Challenge Does not pass)

Tell us what’s happening:

I have completed the challenge Basic Algorithm Scripting: Truncate a String with the following code:

But when i click on Run The tests it does not passes the test. Do I need to use another method or try a different approach?

Your code so far


process.stdin.resume();
process.stdin.setEncoding('utf8');
// Your code here!

var str1="";
var str2="...";
var str3="";

function truncateString(str, num) {
// read the string character by character
for (var i=0; i<num;i++) {
str1 += str[i]

}
str3 = str1+str2
// console.log(str3)
return str3;

}

truncateString("Absolutely Longer", 2)

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36.

Challenge: Truncate a String

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/truncate-a-string

For starters, you are using global variables which do not get reset between each test.

Even if you move the str1, str2, and str2 variables inside your function, your logic is not correct.

Thanks for the advice @RandellDawson. So if I can’t move the varibales inside the loop, what ammendments I should make to make my logic correct?

You need to move the variables inside function (not the loop). But then for the 3rd test case of:

truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length + 2)

your function returns “A-tisket a-tasket A green and yellow basket…”

instead of “A-tisket a-tasket A green and yellow basket”

AND for the 4th test case of:

truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length + 2)

your function returns “A-tisket a-tasket A green and yellow basketundefinedundefined…”

instead of “A-tisket a-tasket A green and yellow basket”.

See if you can figure out what to do about that. The following line will always add the “…” to the end of the string, even if the num value is the greater or equal to the str value’s length. You need some check to only add and truncate if the length of str is longer than num.