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.
0means start at the first character.-1means 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.
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:
Step by Step Execution
Consider this code:
const text = "12345.00";
const result = text.slice(0, -1);
console.log(result);
Step by step:
textcontains eight characters:1,2,3,4,5,.,0, and0.slice(0, -1)starts at index0, the first character.- The end index
-1is counted from the end of the string, so it refers to the position just before the final character. slice()copies every character from the start up to, but not including, that final position.- The final
0is excluded. resultbecomes .
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.
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.(extension)) {
filename;
}
filename.(, -extension.);
}
.(());
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
Comparisons
| Method | Example | Result | Best 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() |
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 includeend.- 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 .
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:
"".(, -);
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.
Keep learning
Related questions
Abort Ajax Requests with jQuery jqXHR.abort()
Learn how to cancel an in-progress jQuery Ajax request with jqXHR.abort(), handle abort status safely, and avoid stale UI updates.
Access the Correct this Inside a JavaScript Callback
Learn why JavaScript this changes in callbacks and how to preserve an object context using bind, arrow functions, and event handler patterns.
Add Key-Value Pairs to JavaScript Objects
Learn how to add key-value pairs to JavaScript objects with dot and bracket notation, dynamic keys, examples, and common mistakes.