Remove last character of String in JavaScript

June 26, 2020

Using substring

substring method returns the part of the string between the start and end index.

let name = `John.k!`;
let first4Char = name.substring(0,4);
console.log(first4Char); // John

To remove the last character we need to get the substring starting from 0 to string length - 1

let name = "John.k!";
let endIndex = name.length - 1;
let result = name.substring(0, endIndex);
console.log(result); // John.k

Using slice

The slice() method extracts a section of a string based on the start & end index. The slice method returns a new string, without modifying the original string.

let name = "JavaScript Jeep";
console.log( name.slice(0, 2) ); // Ja
console.log( name.slice(2) ); // vaScript Jeep

So, to remove the last character from the string we need to slice the string starting from 0th index to the length-1 index

let name = "JavaScript Jeep!";
let endIndex = name.length - 1 ;
console.log(name.slice(0, endIndex));  // JavaScript Jeep

you can also specify endIndex as -1, which represents the last character of string

let name = "JavaScript Jeep!";
console.log(name.slice(0, -1)); // JavaScript Jeep