Remove the last character of String using JavaScript
In this article, quickly we see how to remove the last character of string in JavaScript using the slice()
method and how to use it for more use cases like removing a particular part of the string as substring.
Remove last character of a String
let strVar = 'Hello Poopcoder!'; let editedStr = strVar.slice(0,-1); //'Hello Poopcoder'
Usage
The slice() method extracts parts of a string and returns the extracted parts in a new string. Here we are passing two parameters. Using these parameters we can specify the part of string want to extract.
Syntax
string.slice(start, end)
Parameters | Description |
start | Required. Specifies the index where to begin the extraction. Should be positive value. |
end | Optional. Index where to end the extraction. If omitted it will selects all the character from starting index to end of String. |
More Examples
Example 1:
Extracts whole word.
var str = 'Hello Poopcoder!'; var res = str.slice(0); //'Hello Poopcoder!'
Example 2:
Extracts from index 3 and to the end.
var str = 'Hello Poopcoder!'; var res = str.slice(3); //'lo Poopcoder!'
Example 3:
Extract the characters from position 3 to 8.
var str = "Hello Poopcoder!"; var res = str.slice(3, 8); // 'lo Po'
Example 4:
Extract only the last character.
var str = "Hello Poopcoder!"; var res = str.slice(-1); // '!'
Example 5:
Extract from the character index of and remove the last 3 character.
var str = "Hello Poopcoder!"; var res = str.slice(3,-3); // 'lo Poopcod'