Truncate a String In Javascript With The slice(), substr() And substring() Methods

Published on | by
Reza Baharvand
Updated on
Image for Truncate a String In Javascript With The slice(), substr() And substring() Methods

Introduction

You can shorten a string and limit the character length of a sentence using the slice(), substr(), and substring() methods. You might want to prevent character overflow or shorten the excerpt of a blog post and adding a "read more..." at the end of it.

Also, At the end of this article, I have added a performance comparison between each method.

1. Truncate a String With The slice() Method

Probably the easiest way to shorten a sentence and limit the number of characters is by using the slice() method. It extracts the text from the string and returns a new string without modifying the original string.

const str = "The quick brown fox jumps over the lazy dog."; console.log(str.slice(0, 15)); // "The quick brown"

The slice() method accepts two arguments, beginIndex and endIndex. In the example above, we started chopping the sentence from the starting to character at index[15].

We can concatenate the sliced sentence with ... give it a sense of continuity:

const str = "The quick brown fox jumps over the lazy dog."; console.log(str.slice(0, 15) + "..."); // "The quick brown..."

Since we understand the concept, we can now write a function to take a string and number, then return the truncated sentence.

We can also add a condition to the mix and make sure if the sentence's length is smaller than the number, return the original sentence.

const str = "The quick brown fox jumps over the lazy dog."; function truncate(str, num) { if (str.length > num) { return str.slice(0, num) + "..."; } else { return str; } } truncate(str, 15); // "The quick brown..."

We can write the same function with ternary operators:

const str = "The quick brown fox jumps over the lazy dog."; function truncate(str, num) { let truncatedString = str.length > num ? `${str.slice(0, num)}...` : str; return truncatedString; } truncate(str, 15); // "The quick brown..."

2. The substr() Method

The substr() method is pretty similar to the slice() method. You have to provide a beginIndex and an endIndex.

const str = "The quick brown fox jumps over the lazy dog."; function truncate(str, num) { let truncatedString = str.length > num ? `${str.substr(0, num)}...` : str; return truncatedString; } truncate(str, 15); // "The quick brown..."

3. The substring() Method

The substring() method returns the part of the string between the start and end indexes, or to the end of the string. This method is also similar to the previous one.

Groundhog day again gif

Note that NaN is treated as 0 in this method.

const str = "The quick brown fox jumps over the lazy dog."; function truncate(str, num) { let truncatedString = str.length > num ? `${str.substring(0, num)}...` : str; return truncatedString; } truncate(str, 15); // "The quick brown..."

Performance Comparison

As I was writing this article, I realized all three methods are very similar. So I decided to run a performance comparison. According to the benchmark, using ternary operators decreases the computing time.

I initiated a VERY long string by creating an array and using the toString() method. You can read the "Javascript Array To String" here.

Link to the jsbench.me


Recent Posts

Image for Coin Flip Simulator With Javascript And CSS Animations

Coin Flip Simulator With Javascript And CSS Animations

In this tutorial, you will learn to build a small app to toss a coin using HTML, CSS, and Javascript. The possible outcomes after flipping a coin are either "Head" or "tail". The probability of getting head or tail is 50%.

Image for Use Math.PI To Calculate Area And Circumference Of A Circle

Use Math.PI To Calculate Area And Circumference Of A Circle

The "Math.PI" property returns the PI "π" constant, approximately equal to 3.14159. For example, you can calculate the circumference and surface area of a circle using "Math.PI".

Image for Check If A Function Exists Before Calling With The typeof Operator

Check If A Function Exists Before Calling With The typeof Operator

If you are sharing scripts from different modules or you have a large codebase, you can use the `typeof` operator to check if a function exists.

Image for Create A Toggle Button In Javascript To Manipulate The DOM With The toggle() Method

Create A Toggle Button In Javascript To Manipulate The DOM With The toggle() Method

The "toggle()" is a method of the "DOMTokenList". It removes something like a "class" name from the list, and returns "false". If the "class" name does not exist, it will add it to the list and return "true".