Open In App

JavaScript- Remove Last Characters from JS String

Last Updated : 21 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

These are the following ways to remove first and last characters from a String:

1. Using String slice() Method

The slice() method returns a part of a string by specifying the start and end indices. To remove the last character, we slice the string from the start (index 0) to the second-to-last character.

JavaScript
let str = "Hello GFG";
let res = str.slice(0, -1);
console.log(res); 

Output
Hello GF

2. Using String substring() Method

The substring() method extracts the part of a string between two specified indices. To remove the last character, provide 0 as the starting index and the second-to-last index as the ending index.

JavaScript
let str = "Hello GFG";
let res = str.substring(0, str.length - 1);
console.log(res);

Output
Hello GF

3. Using String substr() Method

The substr() method returns a portion of the string starting from a specified position for a given length. Use it to remove the last character by specifying the starting index and reducing the length by 1.

JavaScript
let str = "Hello GFG";
let res = str.substr(0, str.length - 1);
console.log(res); 

Output
Hello GF

4. Using Array Methods

Convert the string into an array, remove the last element using the pop() method, and join the array back into a string.

JavaScript
let str = "Hello GFG";
let arr = str.split(""); 
arr.pop(); 
let res = arr.join("");
console.log(res); 

Output
Hello GF

5. Using Regular Expression with replace()

Use a regular expression to match and remove the last character of the string.

JavaScript
let str = "Hello GFG";
let res = str.replace(/.$/, ""); 
console.log(res);

Output
Hello GF

6. Using String replace() Without Regular Expressions

Manually specify the last character to be replaced with an empty string using replace() method.

JavaScript
let str = "Hello GFG";
let res = str.replace("G", ""); // Replace the last character
console.log(res);

Output
Hello FG

7. Using String Destructuring and Array slice()

Destructure the string into an array of characters, use slice() to remove the last character, and join it back into a string.

JavaScript
let str = "Hello GFG";
let result = [...str].slice(0, -1).join("");
console.log(result);

Output
Hello GF

8. Using String Trimming

In some cases where the last character is a known whitespace or unwanted character, the trim() method can be used.

JavaScript
let str = "Hello GFG ";
let res = str.trimEnd();
console.log(res);

Output
Hello GFG


Next Article

Similar Reads