5

My task is to "truncate a string (first argument), if it is longer than the given maximum string length (second argument). Return the truncated string with a ... ending.

Note that inserting the three dots to the end will add to the string length.

However, if the given maximum string length num is less than or equal to 3, then the addition of the three dots does not add to the string length in determining the truncated string."

I have written the code:

function truncateString(str, num) {
  if (num > str.length){
    str.slice(num);
    return str.append("...");
  } 
  else if (num < 3) {
    str.slice(3);
    return str.append("...");
  }
  else {
    return "This is not a string";
  }

}

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

However, it's not doing what I need it to do and returns "This is not a string" on every run. Can anyone help me?

4
  • 2
    Is 11 either greater than the length of your string, or less than 3? Commented Apr 18, 2016 at 20:21
  • 11 is the 2nd argument in the function, if str.length < num then it needs to truncate the string by the difference between str.length and num and return a truncated string with ... added to the end of said string. Commented Apr 18, 2016 at 20:27
  • Note that > means "greater than" and < means "less than". Testing str.length < num will give true when the length of the string is less than the value in num. Commented Apr 18, 2016 at 20:31
  • Ahh damn! I'm still getting the two comparatives mixed up. I have to google them every time I use them. But thank you for this :) Commented Apr 18, 2016 at 20:49

12 Answers 12

15

I suggest using instead of ..., because it's a single character.

Then,

function truncate(str, max) {
  return str.length > max ? str.substr(0, max-1) + '…' : str;
}

Note str.substr(0, -1) returns the empty string.

Sign up to request clarification or add additional context in comments.

Comments

4

as @sh-ado-w said above, you should change your conditions, i think this make what you want.

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

}

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

Comments

2

And "This is not a string" is the correct answer, why should it be?

function truncateString(str, num) {
  if (num > str.length){ // if num is greater than string length (in you case 11 is not greater than 43
    str.slice(num);
    return str.append("...");
  } 
  else if (num < 3) {   // or if the num is less than 3 (11 is not less than 3)
    str.slice(3);
    return str.append("...");
  }
  else { // do if no if was matched (and here we are)
    return "This is not a string";
  }

}

So basically what you need is to change > to < in your first if :)

Edit:

The final code you want to have is (str.append() is not a function):

function truncateString(str, num) {
  if (num < str.length){
    str.slice(num);
    return str + "...";
  } 
  else if (num < 3) {
    str.slice(3);
    return str + "...";
  }
  else {
    return "This is not a string";
  }

}

2 Comments

I had a feeling I wasn't too far off having the right answer :) What can you use inside string functions then? Such as .split .splice and .join?
slip is valid but the two are not - check w3schools for reference on javascript string methods w3schools.com/js/js_string_methods.asp
1
    /*This is very late ....but this works. It is all about the boolean comparisons:*/


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

    else if (num>3 || str.length<num){ return str.slice(0,num);}

    else if (str.length>num || num<3){return str.slice(0, num) +"...";}

    }

Comments

1

Those kind of "simple tasks" are usually already solved in major reliable libraries. They deal with it since many years and has been hardly tested: it means that they already solved most of the problems that you could encounter. Even if you don't want to use a library, taking a look at the code could be useful.

Except if you want to learn by practice about re-writing this kind of thing, you should possibly better use Lodash truncate():

_truncate("A-tisket a-tasket A green and yellow basket", {length: 11});
// 'A-tisket...'

Demo code on repl.it.

1 Comment

Note that I also wrote this answer for people coming from Google.
0

Truncate a string (first argument) if it is longer than the given maximum string length (second argument). Return the truncated string with a ... ending.

function truncateString(str, num) {
  if (str.length < num) return str;
  var truncStr = str.slice(0, num);
  var truncStrArr = truncStr.split(' ');
  var truncStrArrLen=truncStrArr.length;
  
  if(truncStrArrLen > 1 &&
    truncStrArr[truncStrArrLen - 1] !== str.split(' ')[truncStrArrLen - 1]) {
    truncStrArr.pop();
    truncStr = truncStrArr.join(' ');
  }
  return str.length > num ? truncStr + '...' : truncStr;
}

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

Comments

0

Here was my solution:

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

Comments

0

its how it works

function truncateString(str, num) {
  // Clear out that junk in your trunk
      var st='';
  if(num>=str.length)
    {

      return str;

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

 else
 if(num<=3){
st = str.slice(0,num);
return st+"...";
 }


}

truncateString("A-", 1);

Comments

0

You can use the below function Parameters str: The string to truncate, firstCharCount: Number of character to show in first portion, endCharCount: Number of characters to show in end portion, dotsCount: Number of dots to in between.

Example truncStringPortion("ID Card Number is 101010",2,6,3) gives output "ID...101010"

function truncStringPortion(str, firstCharCount = str.length, endCharCount = 0, dotCount = 3) {
    var convertedStr="";
    var dotsAdded=false;

    for(var i = 0; i < str.length; i++) {
        if(i < firstCharCount) {
            convertedStr += str.charAt(i);
        }
        else if(!dotsAdded){
            convertedStr += ".".repeat(dotCount);
            dotsAdded=true;
        }
        else if(i > (str.length - endCharCount - 1)) {
            convertedStr += str.charAt(i);
        }
    }
    return convertedStr;
}

Comments

0

Pablo's answer is the neatest one so far.

Making it even shorter and neater with ES6 syntax:

const truncateStr = (str, num) => (num > str.length) ? str : `${str.substring(0, nm)}...`;

Comments

0

function truncateString(str, num){
  if(str.length > num){

return str.slice(0, num) + "..."

  }else {
  return str;
}

}

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
-1

function truncateString(str, num) {

return str.length>num? str.split("").splice(0,num).join("")+"...":str; }

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

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.