There are three ways to remove the last character from a string in JavaScript:
- Method 1: Using the slice() method
- Method 2: Using the substring() method
- Method 3: Using the replace() method
Method 1: Using the slice() method
The slice() method extracts a section of a string and returns it as a new string.
Syntax
string.slice(0, -1);
Visual Representation
let str = "Hello!"
newStr = str.slice(0, -1) //Remove the last character
console.log(newStr)
console.log(str) //original string
Output
Hello
Hello!
In this example, slice(0, -1) extracts the string from the first character (index 0) to one character before the end (index -1 represents the last character).
Method 2: Using the substring() method
The substring() method returns a subset of a string between two indices.
Syntax
string.substring(0, str.length - 1);
Visual Representation
Example
let str = "Hello!"
newStr = str.substring(0, str.length - 1) //Remove the last character
console.log(newStr)
console.log(str) //original string
Output
Hello
Hello!
In this example, Here, substring(0, str.length-1) gets the string from the start up to, but not including, the last character.
Method 3: Using the replace() method
You can remove the last character from a string by using regular expressions with the replace(), applying a pattern that matches the last character and replacing it with an empty string.
Syntax
string.replace(character_to_be_matched, '')
Visual Representation
Example
let str = "Hello!"
newStr = str.replace(/.$/, ''); //Remove the last character
console.log(newStr)
console.log(str) //original string
Output
Hello
Hello!