Join my Laravel for REST API's course on Udemy 👀

Use .slice() to remove the last character of JavaScript Strings

May 26, 2022  ‐ 3 min read

The most convenient way to remove the last character from a JavaScript String object is by making use of the .slice() method.

const name = "Koen";
const result = name.slice(0, -1);
console.log(result);
//=> "Koe"

The two arguments passed to slice() mean the following:

  • The 0 we pass as the first argument to .slice() is the starting-index; from where we want to start slicing.

  • -1, the second argument, is the end-index which indicates up to which character we wish to slice off characters. With negative one we specify the last character of the string.

The .slice() method returns a new string object, leaving the original unchanged.

Description of slice()

The .slice() method extracts a certain portion of a string. To specify this portion we need to pass an index to indicate where to start slicing and optionally one for where to end slicing. If we don't specify an end-index it is assumed that we want to slice to the end of the string.

String.prototype.slice(beginIndex, ?endIndex)

The result that gets returned to us by .slice() is a new String object, the original string won't be mutated.

Thus, to truly remove the last character from the string that is held by a variable we should reassign the result to the original variable.

let name = "Koen";
name = name.slice(0, -1);
console.log(name);
//=> "Koe"

Negative indexing

One part that might be confusing is the negative index of -1. With negative indexes we start at the end of the string and go further backwards once we decrease the negative index.

Thus, a negative index of -1 will return the last character of a string.

const result = "Koen".slice(-1);
console.log(result);
//=> "n"

Slicing off just the last character can be done by first passing the negative string length of -4 and again -1 as the end-index.

const result = "Koen".slice(-4,-1);
console.log(result);
//=> "Koe"

Use substring() to remove the last character

Alternatively we could use the .substring() method instead of .slice(). The downside to this approach is that we cannot make use of negative indexing. Therefore we should find out the necessary end-index via the length of the string.

let name = "Koen";
name = name.substring(0, name.length - 1);
console.log(name);
//=> "Koe"

Remove the first character

We learned to remove the last character from a string, by using the same .slice() we can just as quickly remove the first character from the string.

Instead of passing a negative index to the .slice() method we can pass a positive end-index to the slice of characters from the start of the string.

const result = "Koen".slice(0, 1);
console.log(result);
//=> "oen"

The end-index is non-inclusive, meaning that we slice the string until the index and not up to and including.