Truncate a string

function truncateString(str, num) {
 var a = str.slice(0,num);
  var   b = ""; 
var  c =  str.split(' ');
var  d = a.split(' ');

for (i=0;i<str.length;i++){

if(c[i]===d[i]){
  b +=d[i]+' ';
  
}

  }
    return b+'...';

}

truncateString("Peter Piper picked a peck of pickled peppers", 14);

I don’t know why “return b” showing undefined…
I need help…

a is first num (in this case 14) characters of str. (Peter Piper pi)
c is an array of words from str. (length is 8)
d is an array of words from a. (length is 3)

for loop is looping str.length times (44 times)

So first two times c[i] is equal to d[i], then one time it is not (because picked is shortened to pi), then five times it is not (because if i > 3 d[i] is undefined), then after that c[i] is also undefined and it matches d[i] so it gets added to b.

That’s why return b is showing undefined.

I think you may be misunderstanding the assignment.

You should take the str and return this string shortened to num characters with added ... at the end (three characters). So this line:

var a = str.slice(0,num);

almost does it. You just need to account for additional three characters (...).

function truncateString(str, num) {
var a = str.slice(0,num);
var b = ""; 
var c =  str.split(' ');
var d = a.split(' ');

 if(c[0]===d[0]) {
        if(str.slice(0,num)===str){
              return str;
        }
         for (i=0;i<c.length;i++){

             if(c[i]===d[i]){
                  b +=' '+d[i];
      
             }
           
          }
          return b+'...';      
  }
  
  else{
    return str.slice(0,num)+'...';
  }
}


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

Ok…this is the best I came up with…they only problem i am having is a space here return b +=' '+d[i]; …To separate two strings I am using this.But in the mean time because of this type,I am having an extra space before or after first and last string…How to fix this problem?? Any clue??That will be really helpful…

Can you explain me what are you trying to accomplish with for loop?

As I split both main str and sliced str…I tried to compare each splitted string and take only what matches to each other by a for loop.

ok…i have got it…I also tried num>3 …even though it gives the result…I felt like it’s not the best way to do it.Because if i change the number in function…It doesn’t give the desired result…

function truncateString(str, num) {
if (str.length <= num) {
return str;
} else {
return str.slice(0, num) + ‘…’;
}
}

This is how it is supposed to be. I looked at what the answers were supposed to be and figured out that the length of the string with the … was the same as what the number was. And so I put num as my second parameter in the slice method.