How to remove last character from string in JavaScript

Jun 21, 2023#javascript#how-to

In JavaScript, there are several methods available to remove the last character from a string. One common approach is to use the substring() or slice() methods. Both methods allow you to extract a portion of a string based on the starting and ending indices. By specifying a range that excludes the last character, you effectively remove it from the string.

  1. Using the slice() method, which returns a part of a string based on the start and end indexes.
let str = "Hello world!";
str = str.slice(0, -1); // Remove the last character
console.log(str); // "Hello world"

The slice(0, -1) method removes the last character because -1 means the last index of the string. You can also use str.length - 1 instead of -1 to get the same result.

  1. Using substring() method, which also returns a part of a string based on the start and end indexes.
let str = "Hello world!";
str = str.substring(0, str.length - 1); // Remove the last character
console.log(str); // "Hello world"

The substring(0, str.length - 1) method removes the last character because str.length - 1 is the last index of the string. You cannot use negative indexes with substring().

  1. Using the replace() method, which returns a new string with one, some, or all matches of a pattern replaced by a replacement. The pattern can be a string or regular expression, and the replacement can be a string or a function called for each match.
let str = "Hello World!";
str = str.replace(/.$/, "");
console.log(str); // "Hello World"

The . within the regular expression represents any character, and the $ denotes the end of the string. So, .$ matches the last character in the string. By replacing it with an empty string, that character is removed.

Please note that if the string contains newline characters or multiple Unicode code points, the regular expression approach may not behave as expected. In such cases, using substring() or slice() methods might be more suitable.