Truncate a string JavaScript

javascript truncate string with dots
truncate string java
javascript truncate string at character
javascript string slice
javascript string substring
jquery truncate string
javascript string length
javascript substring indexof

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?

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";
  }

}

freeCodeCamp Challenge Guide: Truncate a String - Guide, Strings are immutable in JavaScript so we will need a new variable to store the truncated string. Hint 2. You will need to use the slice() method and specify where​  Truncate a string (first argument) if it is longer than the given maximum string length (second argument). Return the truncated string with a ending.

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.

JavaScript: Truncate a string if it is longer than the specified number , Truncated strings will end with a translatable ellipsis sequence ("…") (by default) or specified characters. Test Data: console.log(text_truncate('We  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.

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)

Truncate a string straight JavaScript, Use the substring method: var length = 3; var myString = "ABCDEFG"; var myTruncatedString = myString.substring(0,length); // The value of  It has a truncate method that is pretty smart. From the documentation: Truncates a string. Unless split is true, truncate will not split words up, and instead discard the word where the truncation occurred. Example: 'just sittin on the dock of the bay'.truncate(20) Output: just sitting on

    /*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) +"...";}

    }

JavaScript String substring() Method, Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java  Single and double quotes come from ancient times of language creation when the need for multiline strings was not taken into account. Backticks appeared much later and thus are more versatile. Backticks also allow us to specify a “template function” before the first backtick. The syntax is: func`string`.

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));

How to truncate text with vanilla JavaScript, We'll use the split() method, passing in a space as the character to split our string by. var truncate = function (elem, limit)  And finally, if you have a number in [−2147483648, 2147483647], you can truncate to 32 bits using any bitwise operator. | 0 is common, and >>> 0 can be used to obtain an unsigned 32-bit integer: Math.floor() will give the wrong result for negative numbers. Consider mozey's answer below for better alternatives.

String.prototype.substring(), The substring() method returns the part of the string between the start and end indexes, or to the end of the string. const str = 'Mozilla'  No point in using string.substring(0, length) in the else case, since the string is guaranteed to be <= 20 chars at that point, just use string. I suggest to use an extension for code neatness. Note that extending an internal object prototype could potentially mess with libraries that depend on them.

JavaScript Algorithm: Truncate a String, We are going to write a function called truncateString that will accept a string ( str ) and an integer ( num ) as arguments. The goal of the function  Definition and Usage. The substring() method extracts the characters from a string, between two specified indices, and returns the new sub string. This method extracts the characters in a string between "start" and "end", not including "end" itself.

How to truncate string in Javascript?, In this article, you are going to learn how to truncate a string in Javascript. We are going to create a function that will accept two parameters. Truncating numbers in Javascript Math.trunc() simply removes all the fractional digits. It takes one argument which is a number. If the argument is a positive number it behaves exactly the same as Math.floor().

Comments
  • Is 11 either greater than the length of your string, or less than 3?
  • 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.
  • 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.
  • 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 :)
  • 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
  • Note that I also wrote this answer for people coming from Google.