Truncate String in JavaScript

Truncate String in JavaScript | If a string is greater than the allotted maximum length, a function is created that will truncate the text. We’ll create a function named truncateString that takes two parameters: a string (str) and an integer (num). We will discover how to truncate a string in JavaScript in this article. We’re going to develop a function that takes two inputs. The first one is the actual string, and the second is the maximum number of characters in the string that we will accept before truncating it.

If the length of the string is less than or equal to the maximum length, the logic will not truncate it; otherwise, it will be truncated and the trailing dots will be added to show that it has already been truncated.

The function checks to determine whether the length of the supplied string exceeds the maximum permissible string length (num). If it is, cut the string off exactly at the limit and output it with an ellipsis (…). Return the string in its original form if it is shorter than the cutoff length of the string or equal to it.


str = “Know-Program – Learn to code.”;
num = 8;

The string break is 8 characters for the aforementioned case. Given that the string is lengthier than eight characters, we truncate it to 8 characters and then return it with an ellipsis. So the expected output here would be “Know-Pro…”

It is necessary for us to create a JavaScript function that accepts a string and a number as arguments. These three duties are meant to be carried out by our role:

  • If the specified maximum string length (second parameter) is exceeded, truncate the string (first argument) and return the truncated text with a … ending.
  • The three dots that were added at the end will lengthen the string as well.
  • The three dots should not, though, be added to the string length when establishing the truncated string if the specified maximum string length is less than or equivalent to 3.

Program to Truncate String in JavaScript

const truncate = (str, len) => {
    if (str.length > len) {
        if (len <= 3) {
            return str.slice(0, len - 3) + "...";
        else {
            return str.slice(0, len) + "...";
    else {
        return str;

const string = 'Know-Program - Learn to Code';
const str1 = 'Hello';

console.log(truncate(string, 5));
console.log(truncate(str1, 2));



If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *