How to Remove Last Character from String in JavaScript
Table of Contents
Knowing how to manipulate strings is a basic skill to have in any programming language.
A common manipulation of strings is needing to remove the last character from a string.
In this post, we'll learn how to remove the last character from a string in JavaScript.
Slice
The easiest way to remove the last character from a string is to use the slice()
method.
The slice()
method takes two arguments, the first is the index of the character you want to start from, and the second is the index of the character you want to stop at.
We can take advantage of the fact that it supports negative numbers to tell it to seek from the end of the string.
Let's use this as our example string:
JAVASCRIPTconst string = "Hello World!";
Now let's use slice()
with the first argument being 0
and the second argument being -1
to exclude the last character from the string.
JAVASCRIPTconst string = "Hello World!";
const newString = string.slice(0, -1);
console.log(newString); // "Hello World"
Substring
Another way to remove the last character from a string is to use the substring()
method.
This method similarly takes two arguments, except it does not support negative numbers.
Because of this, we will need to pass it the length of the string minus 1 to get the index of the last character.
JAVASCRIPTconst string = "Hello World!";
const newString = string.substring(0, string.length - 1);
console.log(newString); // "Hello World"
Conclusion
In this post, we learn the two easiest ways to remove the last character from a string.
You can either use slice()
or substring()
to accomplish this task.
Hopefully, you've found this useful. Thanks for reading!
- Getting Started with Svelte
- Create an RSS Reader in Node
- How to Set Up Cron Jobs in Linux
- How to build a Discord bot using TypeScript
- How to deploy a Node app using Docker
- Using Puppeteer and Jest for End-to-End Testing
- Getting Started with Handlebars.js
- Creating a Twitter bot with Node.js
- Using Push.js to Display Web Browser Notifications
- Setting Up Stylus CSS Preprocessor
- Setting Up a Local Web Server using Node.js
- Using Axios to Pull Data from a REST API