Javascript Remove Last Character From String

Javascript Remove Last Character : In this tutorial we will study the different methods to remove the last character of a string in the Javascript language.
Introduction
In some situations, it may be necessary to delete the last character of a string. In Javascript, there are several ways to do this:
- Remove the last character using the slice() function.
- Remove the last character using the substring() function.
- Remove the last character using the substr() function.
In the rest of this tutorial I will explain how to use these 3 Javascript functions with some examples.
Javascript Remove Last Character From String
Using slice()
function
The slice() function extracts the sub-string between the indexes specified in the function. It takes 2 arguments: the beginning of the index or the beginning of the extraction. This is the starting point of the string to be extracted. The second argument represents the end of the index to indicate the end of the extraction.
Here is the syntax of the function :
# Using slice() function
str.slice(start, end);
In the second argument it is possible to specify a negative number for deletion starts at the end of the string. It is thanks to this specificity that we can directly delete the last character of a string. Here is how to proceed :
var website= "AMIRADATA";
var websiteR = website.slice(0, -1);
console.log(websiteR);
Output :
AMIRADAT
Note: The slice() method does not modify the original string. We need to create a new variable that will store the result of the function.
Using substring()
function
The substring() function returns substring of the string between the specified indexes. This function takes two arguments, the start and end point of the substring.
Here is the syntax of the function :
# Using substring() function
str.substring(start, end);
To delete the last character of a string, we must take as a starting point 0 and in the second argument get the total length of the string (thanks to the function str.length) and then subtract 1 from this value.
Example of the use of the substring() function:
var website= "AMIRADATA";
var websiteR = website.substring(0, website.length - 1);
console.log(websiteR);
Output:
AMIRADAT
Using substr()
function
The substr() function works on the same principle as the substring() function.
Here is the syntax :
# Using substr() function
str.substr(start, length);
And an example of how to use it :
var website= "AMIRADATA";
var websiteR = website.substr(0, website.length - 1);
console.log(websiteR);
Output:
AMIRADAT
Conclusion
In this article, we have that there are several methods to remove the last character of a string. None is really better than another. It is up to you to choose the one that seems the easiest to understand.
If you have any questions or remarks about this article, don’t hesitate to leave me a comment!
See you soon.
Comments
Leave a comment