Removing last character using javascript – substring, substr, slice methods

javascript-slice-substr-substring

In this post, I would like to present you with 3 different 1-line scripts that are used a lot. These snippets are used to remove the last character from a string. When may you need this? You may be building up a string in a loop, and you might be adding a separatorĀ at each iteration to the end. Now, you want to remove the last unneeded separator character using javascript before sending it in an ajax request. In Javascript, there is a “String” object and there are string literals. You can call any string method on a literal or on a string object. Here we will use “substring”, “substr” and “slice” methods.

In Javascript, there is a “String” object and there are string literals. You can call any string method on a literal or on a string object. Here we will use “substring”, “substr” and “slice” methods.

Use “substring” method to remove the last character from a string using javascript:

substring method extracts the characters from a string, between two specified indices.

Use “substr” method to remove the last character from a string using javascript:

substr method extracts the characters from a string, beginning at a specified start position, and through the specified number of character.

Use “slice” method to remove the last character from a string using javascript:

slice method extracts a part of a string and returns a new string. (string.slice(start, end))

The basic difference between substring, substr and slice methods is, substring and slice take 2 indices (start and end positions) to extract the desired string, while substrĀ takes a starting position and a length to do the same thing.

Hope this helps.
Good Luck,
Serdar