Truncate string - understanding why this works

Truncate string - understanding why this works
0

#1

So this must be a very simple explanation but I would like to understand why my second “if” statement returns “true” even though I have a string with the length of 1 and a num with a value of 1. I tried marking up my code using ` but for some reason it’s not working :confused:

Anyways, the question is why does my second if statement return true and executes the command when 1 clearly isn’t > than 1.

Thanks

function truncateString(str, num) {
  if (str.length > num && num >= 3){
    return str.slice(0, num - 3) + "...";
  } 
  
  if (str.length > num && num <= 3){
    return str.slice(0, num) + "...";
  } 
  else {
    return str.slice(0);
  } 
}

truncateString("A", 1);

#2

I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.


#3

The condition in the second if-block is false. What gets executed is the last return line.


#4

In your example of

truncate("A",1);

The second if statement does not execute. The else statement executes instead. Do you have an example of when the 2nd if statement returns true when you do not expect it?


#5

@kevcomedia I think our replies were 1ms apart.


#6

Whoops! I can’t believe I didn’t catch that. Haha, thanks for the help.


#8

Here is my code.


function truncateString(str, num) {

if(str.length >  num ){
return ( str.substr (0,num)  + '...');
  }
return ( str.substr (0,num));
}



#9

This is how i did it :slight_smile:

function truncateString(str, num) {
  if (str.length > num) {
     return str.slice(0, num) + "...";  
  } else {
     return str.slice(0, num);
  }
}

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

#10
function truncateString(str, num) {
  var newStr = str.substring(0, num);
  var res = (num >= str.length ? newStr : newStr + "...");
  return res;
}


#11

The fast way. Loving ternary operator!

function truncateString(str, num) {
  // Clear out that junk in your trunk
  return (str.length > num ? (str.substring(0, num) + '...'):str);
}