Display only the first x characters (or words) of a string using JavaScript

Nikhil Vijayan
2 min readApr 20, 2019

Sometimes, when designing for interfaces, there’s just way too much content (for the given context) to display on a particular screen. Often, the user might not need to see all the information right away. I’ve run into this issue a few times, mostly while making cards out of some data coming from a database or an API endpoint.

Two ways of only displaying the first x characters (or words) using JavaScript

  1. Using slice()
const string = "In an age when nature and magic rule the world, there is an extraordinary legend: the story of a warrior who communicates with animals, who fights sorcery and the unnatural. His name is Dar, last of his tribe. He is also called Beastmaster."// slice(start, stop)string.slice(0, 50)// => returns "In an age when nature and magic rule the world, th"

You can also use slice() like so:

string.split(' ').slice(0, 5).join(' ')// => "In an age when nature"

The split(' ').slice(start, stop).join(' ') approach above doesn’t cut any words short.

2. Using substring()

const string = "In an age when nature and magic rule the world, there is an extraordinary legend: the story of a warrior who communicates with animals, who fights sorcery and the unnatural. His name is Dar, last of his tribe. He is also called Beastmaster."// substring(start, stop)string.substring(0, 50)// => returns "In an age when nature and magic rule the world, th"

Things to note:

  • Both slice() and substring() returns a new string, and do not mutate the original string.
  • Using slice(), If start > stop, returns an empty string "".
string.slice(10, 1)
// => ""
  • Using substring(), if start > stop, it swaps out those 2 arguments
string.substring(10, 1)
// => "n an age "
  • Using substring(), if a character is negative, it will treat it as if its zero
string.substring(-1, 10)
// => "In an age "

There are some more peculiarities that you can find in this details SO response.

--

--