Tell us what’s happening:
Please help me with this one!!
I was not able to add " . . . " at the end of the str1
Wouldn’t it be possible in the above manner without using slice??```
Your code so far
function truncateString(str, num) {
let str1= “”;
for (let i=0; i <= num; i++)
str1 += str[i];
return str1;
}
console.log(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
I’ve edited your code 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.
function truncateString(str, num) {
let str1 = "";
for (let i = 0; i <= num; i++) {
str1 = str1 + str[i] ;
}
return str1 + "...";
}
console.log(truncateString("A-tisket a-tasket A green and yellow basket", 8))
If you look at the console you should see a space between the words and the …
Adding {"here also"} to that line of code just breaks your code because it is bad syntax. If you want to comment a line of code you use // comment.
There are three things which you need to consider:
Zero-based indexing. Your for loop needs to stop at the correct string index.
You only concatenate “…” onto a truncated string. If number supplied to the function matches the length of the original string, you would be returning the whole string.
You need to also consider what happens when you supply a number to the function which is greater than the length of the input string.
function truncateString(str, num) {
let str1= "";
for (let i = 0; i <= num; i++) {
if (str.length > num) {
str1 += str[i];
} else {
return str;
}
}
return str1;
}
console.log(truncateString("A-tisket a-tasket A green and yellow basket", 8));
But, I was unable to pass the other tests
where should I add this // " . . . "
You still need to modify the for loop to account for zero-based indexing, specifically this bit: i <= num.
You’re now not concatenating “…” onto a truncated string, so you need to do this (in your return statement perhaps)?
The reason I mentioned // comment is that you had {“here also”} tagged onto the end of a line originally, and I guessed that perhaps you were trying to comment your code? You should always feel free to add comments to your code if it helps you (or others) understand your code better, but certainly not a requirement!