2 4 Votes

JavaScript: Remove last character from string

Tip by Progger99 | Last Update on 06/01/2019 | Created on 08/02/2012

Often, we want to remove the last character from a string in JavaScript. Here is how to do it:

var strold = '1,2,3,';
var strnew = strold.substr(0, strnew.length-1);
alert(strnew);
// output: '1,2,3'

In the example, we have specified a string "strold", which has a comma too much at its end, we want to remove. The new string should be later stored in the variable "strnew". 

We are using the method substr(), which allows us to return parts of a string. Substr() takes two parameters: The first parameter is the location of the start and the second parameter is the length of our substring (number of characters).

In order to delete the last character, we proceed as follows: We want to extract a substring starting from the first character of the original string. So our first parameter is 0, because in JavaScript, the first character is the 0th character. From this character on, we want to keep as many characters as the string is long up to one character at the end. So, we can get the length of the old string with "strold.length" and simply subtract 1.

Delete first and last character

To illustrate this, here is just another example in which we want to delete the first and the last character from a string in JavaScript:

var strold = '12345';
var strnew = strold.substr(1, strold.length-2);
alert(strnew);
// output: '234'

If we also do not want to keep the first character of the string, we have to start at 1 rather than at 0. Thus, our first parameter is 1, so that we can cut the first letter of the string. From this character on, we want to keep as many characters as the string length minus 2. If we would subtract 1 again as in the last example, we would keep our last character here, because this time, we are starting one character from the beginning.

ReplyPositiveNegativeDateVotes

Alvin

Show Profile | Message
Avatar
00 Votes

substr() is a Javascript string method, not—strictly speaking—a function. Otherwise this is an excellent tip.
06/01/2019 at 00:42

ReplyPositive Negative

Progger99

Show Profile | Message
Avatar
00 Votes

Thank you very much for that hint, I have corrected it in my article.

Perhaps you can create an own article, explaining the difference between functions and methods. That would be very interesting.
06/01/2019 at 19:59

Positive Negative
Reply

About the Author

Avatar AuthorThe author has not added a short description to his profile yet.
Show Profile | Message

 

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own articles on askingbox.com. How to do.