Truncate A String in JavaScript with Example


This short tutorial is on how to truncate a string or a paragraph in JavaScript.

We usually truncate a string when the string is very long and we want to display the string only up-to a few characters in our web-page.

Example of a truncate (string with dots) string:

This is a webpage about...

So In JavaScript we have different ways but in this tutorial we will use slice() method to truncate a string.

The slice() method is use to extract a part of a string and return us the extracted part as a new string.

Syntax:

String.slice(start, end)

The start parameter defines the part from where you want to extract.

The end defines till where you want it extract the string.

Let's see slice method in action :

let text = "Hello This is a method to extract string";
let result = text.slice(0, 25);

console.log(result)

Output:

Hello This is a method to

As you can see the slice is from position 0(start) to 25(end). So 25 character (including space) is extracted from the string.

Now, we can use create a function to truncate a string in JavaScript. And the function will take two argument from us:

  1. The String and
  2. The max limit (end value)
function truncateStr(str, limit){
  // code to shorten string here
}

And inside the function we will have a if..else statement to check if the length of the string is greater then the max limit or not.

function truncateStr(str, limit){
  if(str.length > limit){
    // truncate string
  } else {
    // return the original string
  }
}

If the length is greater then it will truncate the string using slice() method and append ... to it at the end , else it will return back the original string.

let string = "Hello This is a method to extract string";
function truncateStr(str, limit){
  if(str.length > limit){
    // truncate string
     return str.slice(0, limit) + "..."
  } else {
    return str;
  }
} 

console.log(truncateStr(string, 25))

Output:

Hello This is a method to...

You can write the same function in ES6 shorter version using template literals like this:

let string = "Hello This is a method to extract string";
const truncateStr = (str, limit) => str.length > limit ? `${str.slice(0,limit)}...` : str

console.log(truncateStr(string, 25))

Output:

Hello This is a method to...

NOTE:

You can also use JavaScript methods like substr() or substring() instead of slice().

Related Topics:

String Interpolation In JavaScript

Remove Whitespace From JavaScript String

How To Remove Character From A String In JavaScript.

How To Remove Last Character From A String In Javascript

Check If A String Contains A Substring In Javascript

How to compare two strings in JavaScript?

Capitalize First Letter Of A String In JavaScript


💾 Recommended Articles