Remove Last Character from a String in JavaScript
How to remove last character from a string in JavaScript or jQuery or Node.js script. In this post, we will see how to remove the last character from a string in JavaScript. This post describes 3 possible methods to remove the last character from a string in JavaScript. You can use any one of the following methods to remove the last character from a string in JavaScript.
3 Methods to Remove Last Character from a String in JavaScript
JavaScript Provides a wide range of string handling functions. There are three straightforward functions substring()
, slice()
, or substr()
to do this task.
1. Using substring()
function
The substring()
function returns the part of the string between the specified indexes. This function takes two arguments, the starting point of the substring, and the ending point of the substring. 0 as the starting point, and the length of the original string minus 1 as the ending point. This will return the original string minus the last character of the string.
Syntax
str.substring(start, end);
Example
var str= "Hello World!";
var newstr = str.substring(0, str.length - 1);
console.log(newstr);
Output
2. Using slice()
function
The slice()
function works similarly. This method extracts the text from a string between the specified indexes and returns a part of the substring.
The first argument is the index where to begin the extraction. However, the second argument is optional where to end the extraction. You can see a negative number to select from the end of the string.
You can use the following code to remove the last character from the string.
Syntax
str.slice(start, end);
Example
var str= "Hello World!";
var newstr = str.slice(0, -1);
console.log(newstr);
Output
We prefer to use the slice()
function to remove the last character from the string.
3. Using substr()
function
The substr()
method returns a part of the string, starting at the specified index and extracting the specified number of characters.
Syntax
str.substr(start, length);
Example
var str= "Hello World!";
var newstr = str.substr(0, str.length - 1);
console.log(newstr);
Output
Difference between substr()
vs substring()
As you see above both functions syntax, the difference is in the second argument. The second argument to substring()
is the index to the end of extracting, but the second argument to substr()
is the maximum length to return.
We hope you have found this article helpful. Let us know your questions or feedback if any through the comment section in below. You can subscribe our newsletter and get notified when we publish new WordPress articles for free. Moreover, you can explore here other JavaScript related articles.
Icon credit: Samat Odedara
If you like our article, please consider buying a coffee for us.
Thanks for your support!
Buy me a coffee!
Join the Discussion.