DEV Community

Jesse
Jesse

Posted on

Control text excerpt length with JavaScript

Why not use CSS?

The CSS version works just fine and there are actually a couple ways you can pull it off. But, it feels like a bit of a "hack" to me. Using JavaScript feels more purposeful and makes a little more sense in my opinion.

Let's get started

Write a function

function myFunction() {

The string

You'll need to assign a variable for your string. For this example, I'll write the string in:
var str = "Killua Zoldyck is the best friend of Gon Freecss";

If you're trying to pull all excerpts in your blog, you'll need to find the class name used and call that in:
var str = document.getElementByClassName("my_excerpt");

The output

Next, you'll need to define a space to insert your excerpt in the HTML:
var output = document.getElementById("excerpt_area");

The if statement

The first thing we want to do here is decide our character length. For this example, we'll set it to 10 characters.
So, let's start by checking if our string is greater than 10 characters using .length:
if (str.length > 10) {

Next, let's tell our function what to do if that criteria is met. We'll need to only show part of the string using .substring() which requires two arguments: a start and end point in the string. We'll tell it to start at character 0 and end at character 10:
str = str.substring(0,10);

Optional:
I like to show the user that we're clipping the text by adding three periods. We can simply add on to our if statement:
str = str.substring(0,10) + "...";

Lastly, we can close our if statement.

Showing the excerpt

Using the output variable we defined, we can use .innerHTML to print our excerpt:
output.innerHTML = str;

We place this outside the if statement so that any excerpts below 10 characters will still be shown in the HTML.

The end result should show: "Killua Zol..."

Full code snippet:

function myFunction() {
    var str = "Killua Zoldyck is the best friend of Gon Freecss";
    var output = document.getElementById("excerpt_area");
    if (str.length > 10) {
        str = str.substring(0,10) + "...";
    }
    output.innerHTML = str;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)