How to remove last character from string in JavaScript

Updated Jan 31, 2024#javascript#strings

There are many scenarios where you may need to remove the last character from a string. For example, you may want to:

  • Remove a trailing slash or comma from a URL or a list
  • Remove a newline or carriage return character from a text file
  • Remove a punctuation mark from a sentence or a word
  • Remove a digit or a letter from a number or a code

In JavaScript, common approachs are to use the substring() or slice(), which 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.

Using slice method

The slice() method of String is used to extract a part of a string and return it as a new string, without modifying the original string. You can specify the start and end indexes of the extracted part, or use negative indexes to count from the end of the string.

let str = "Hello world!";
str = str.slice(0, -1);
console.log(str); // "Hello world"

Here slice(0, -1) 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.

Using substring method

The substring() method of String is used to return a part of the string from a start index to an end index, excluding the end index. It does not change the original string, but returns a new string.

let str = "Hello world!";
str = str.substring(0, str.length - 1);
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().

Using replace method

The replace() method 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.