Question

Remove the Last Character from a JavaScript String

javascriptslicetrim

Question

Given the JavaScript string "12345.00", how can you remove its final character so that the result is "12345.0"?

trim() appears to remove whitespace only. How can slice() or another JavaScript string method be used for this task?

Short Answer

You will learn how to remove the last character from a JavaScript string using slice(0, -1). You will also see why strings are immutable, how to handle empty strings safely, and when numeric formatting is a better solution than removing characters.

Concept

JavaScript provides several methods for extracting part of a string. The most direct method for removing the final character is slice().

const value = "12345.00";
const result = value.slice(0, -1);

console.log(result); // "12345.0"

slice(start, end) returns a new string beginning at start and ending before end.

  • 0 means start at the first character.
  • -1 means one character before the end.

Strings are immutable in JavaScript: a string cannot be changed in place. Methods such as slice() return a new string, so you must store or use the returned value.

trim() is not designed for this job. It removes whitespace at the beginning and end of a string, not arbitrary characters such as 0.

Mental Model

Think of a string as a row of numbered tiles:

"12345.00"
 01234567

Calling slice(0, -1) means:

  • Start at tile 0.
  • Copy tiles until one tile before the end.

The final 0 is left out, producing:

"12345.0"

The original row of tiles remains unchanged. JavaScript gives you a newly copied row instead.

Take Quiz

Syntax and Examples

The usual syntax is:

const shortened = text.slice(0, -1);

Basic example

const price = "12345.00";
const priceWithoutLastCharacter = price.slice(0, -1);

console.log(priceWithoutLastCharacter); // "12345.0"
console.log(price); // "12345.00"

price is unchanged because strings are immutable.

Remove more than one character

Use a more negative end index to omit more characters:

const filename = "report.pdf";

console.log(filename.slice(0, -4)); // "report"

Equivalent positive-index form

You can calculate the ending position with length:

const text = "hello";
const result = text.slice(0, text.length - 1);

console.log(result); // "hell"

For removing the last character, slice(0, -1) is usually shorter and clearer.

Step by Step Execution

Consider this code:

const text = "12345.00";
const result = text.slice(0, -1);

console.log(result);

Step by step:

  1. text contains eight characters: 1, 2, 3, 4, 5, ., 0, and 0.
  2. slice(0, -1) starts at index 0, the first character.
  3. The end index -1 is counted from the end of the string, so it refers to the position just before the final character.
  4. slice() copies every character from the start up to, but not including, that final position.
  5. The final 0 is excluded.
  6. result becomes "12345.0".
  7. console.log(result) prints 12345.0.

A shorter trace:

Input:  "12345.00"
slice:  [start: 0, end: -1]
Output: "12345.0"

Real World Use Cases

Removing a final character is useful when the character is known to be unwanted or is a delimiter.

  • Removing a trailing comma before displaying manually built text: "red,green," → "red,green".
  • Removing a final newline from text read from a source that adds one.
  • Removing a suffix such as a known file extension when another method is not needed.
  • Cleaning an identifier after a scanner or parser appends a separator.
  • Editing user-entered text in a simple backspace-style interface.

For numeric values, be careful. Removing the last character is a text operation, not numeric rounding or formatting. If the intent is to control decimal places, use number formatting instead.

Take Quiz

Real Codebase Usage

In production code, developers often check a condition before removing text. This prevents accidentally removing a valid final character.

Remove a character only when it matches

function removeTrailingComma(text) {
  if (!text.endsWith(",")) {
    return text;
  }

  return text.slice(0, -1);
}

console.log(removeTrailingComma("one,two,")); // "one,two"
console.log(removeTrailingComma("one,two"));  // "one,two"

This is a guard clause: if there is nothing to remove, return early.

Remove a known suffix

For a complete suffix, endsWith() plus slice() makes the intent clear:

function removeJsonExtension(filename) {
  const extension = ".json";

  if (!filename.endsWith(extension)) {
    return filename;
  }

  return filename.slice(0, -extension.length);
}

console.log(removeJsonExtension("settings.json")); // "settings"

Format a number when the requirement is numeric

If 12345.00 represents a number and you want one decimal place, use toFixed(1):

const amount = 12345.00;
const displayAmount = amount.toFixed(1);

console.log(displayAmount); // "12345.0"

toFixed() returns a string suitable for display. It rounds when necessary, unlike slice(), which only removes characters.

Common Mistakes

Expecting trim() to remove zeroes

trim() removes whitespace, not arbitrary characters.

const value = "12345.00";
console.log(value.trim()); // "12345.00"

Use slice(0, -1) when you specifically want to remove the final character.

Forgetting to save the returned string

This does not modify text:

let text = "hello";
text.slice(0, -1);

console.log(text); // "hello"

Assign the result:

text = text.slice(0, -1);
console.log(text); // "hell"

Using slice(-1) by itself

slice(-1) returns only the last character; it does not remove it.

const text = "hello";
console.log(text.slice(-1)); // "o"

Use slice(0, -1) to return everything except the last character.

Removing a character without checking it

This can corrupt valid data:

const filename = "photo";
const result = filename.slice(0, -1);

console.log(result); // "phot"

When removing a delimiter or suffix, verify it first with endsWith().

Treating a formatting problem as text chopping

const amount = 19.99;
console.log(String(amount).slice(0, -1)); // "19.9"

This is not reliable rounding. Use amount.toFixed(1) when you need a defined number of decimal places.

Ignoring empty strings

This is safe but may not match your business rule:

console.log("".slice(0, -1)); // ""

Decide whether an empty input should stay empty, produce an error, or be rejected during validation.

Comparisons

MethodExampleResultBest use
slice(0, -1)"hello".slice(0, -1)"hell"Clear, common way to remove the last character
slice(0, text.length - 1)"hello".slice(0, 4)"hell"Useful when the end position is calculated
substring(0, text.length - 1)"hello".substring(0, 4)"hell"Works for positive indexes, but does not support negative indexes as expected
trim()" hi ".trim()"hi"Removing surrounding whitespace only
replace(/.$/, "")"hello".replace(/.$/, "")"hell"Pattern-based removal; unnecessary for a simple final character
toFixed(1)(12345).toFixed(1)"12345.0"Numeric display formatting and rounding

For this specific task, prefer:

text.slice(0, -1);

Avoid substring(0, -1): unlike slice(), substring() treats negative values as 0, so it will not remove the last character.

Take Quiz

Cheat Sheet

// Remove the final character
const result = text.slice(0, -1);

// Remove the final 3 characters
const result = text.slice(0, -3);

// Get only the final character
const lastCharacter = text.slice(-1);

// Remove a known suffix safely
const result = text.endsWith(".js")
  ? text.slice(0, -3)
  : text;

// Format a number to one decimal place
const display = Number(value).toFixed(1);

Key rules:

  • slice(start, end) does not include end.
  • Negative indexes count from the end of the string.
  • slice(0, -1) excludes one character from the end.
  • Strings are immutable; save the returned value.
  • Use trim() for whitespace, not for arbitrary characters.
  • Use toFixed() for decimal formatting, not slice().

FAQ

How do I remove the last character of a string in JavaScript?

Use slice(0, -1):

const result = "12345.00".slice(0, -1);
// "12345.0"

Does slice(0, -1) change the original string?

No. JavaScript strings are immutable. slice() returns a new string.

What does -1 mean in slice()?

It counts from the end. In slice(0, -1), it means stop just before the last character.

Why does trim() not remove the final 0?

trim() only removes whitespace such as spaces, tabs, and line breaks at the start and end of a string.

What happens if I call slice(0, -1) on an empty string?

It returns another empty string:

"".slice(0, -1); // ""

Should I use slice() to format decimal numbers?

Usually no. Use toFixed() when you need a particular number of decimal places, because it handles rounding:

(12.39).toFixed(1); // "12.4"

Can I remove the last character only if it is a comma?

Yes. Check it first with endsWith():

const result = text.endsWith(",") ? text.slice(0, -1) : text;
Take Quiz

Mini Project

Description

Build a small text-cleaning utility that removes a trailing delimiter only when it exists. This mirrors a common task when preparing comma-separated tags, query parameters, or generated text for display.

Goal

Create a function that safely removes one trailing comma from a string without changing text that does not end in a comma.

Requirements

  • Create a function named removeTrailingComma.
  • Accept a string argument.
  • Remove exactly one comma when the string ends with a comma.
  • Return the original text when it does not end with a comma.
  • Handle an empty string without throwing an error.
Take Quiz

Keep learning

Related questions

View more