by Sai gowtham

How to remove the last character from a string in JavaScript

How to remove the last character from a string in JavaScript

In this tutorial, we are going to learn about different ways to remove the last character from string in JavaScript.

First way: slice method

In JavaScript, we have slice() method by using that we can remove the last character from a string instead of modifying the original string.

Example:

let str  = 'hello/';


console.log(str.slice(0,str.length-1));

//output-->   'hello'

slice method takes two arguments startIndex and endIndex.

startIndex is included in the output.

endIndex is not included in the output.

Second way: substring method

Example:

let str  = 'hello/';

console.log(str.substring(0,str.length-1));

//output--> 'hello'

substring method also works similar like slice method but in substring method if argument one index is greater than argument two index then arguments are swapped.

Example:

let str  = 'hello/';

//this syntax also gives correct answer
// because argument 1 index is greater than argument 2
console.log(str.substring(str.length-1,0));

//output--> 'hello'

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
26,545 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
221,520 students enrolled
44 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
114,575 students enrolled
21 hours of video content
View Course