0

Remove Last Character From String in Javascript

Posted by Will on November 8, 2018

Javascript provides a wide array of string-handling functions. Removing the last character from a string is a simple task in Javascript. There are two very straightforward ways to go about this task, and either one works fine.

Substring

The substring function in Javascript takes two arguments, the starting point of the substring, and the ending point of the substring. By calling substring with 0 as the starting point, and the length of the original string minus one as the ending point, Javascript will return the original string minus the last character.

var theString = 'Angus Macgyver!';
var theStringMinusOne = theString.substring(0, theString.length-1);
alert(theStringMinusOne);

That should pop up “Angus Macgyver”, without the exclamation point.

Slice

The slice function works similarly.

var theString = 'Angus Macgyver!';
var theStringMinusOne = theString.slice(0, -1);
alert(theStringMinusOne);

I personally like the first option as substring is a familiar function across various languages. Honestly, there’s no difference though – pick your pleasure.

Leave a Reply

Your email address will not be published. Required fields are marked *