Open In App

JavaScript Program to Remove First and Last Characters from a String

Last Updated : 13 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

This article will show you how to remove the first and last characters from a given string in JavaScript. There are two methods to remove the first and last characters in a string.

  • Using String slice() Method
  • Using String substring() Method

Using String slice() Method

The string.slice() method returns a part or slice of the given input string.

Syntax:

string.slice(startingIndex, endingIndex)

Example: In this example, we will remove the first and the last character of the string using the slice method in JavaScript.

Javascript




// JavaScript Program to remoove first 
// and last character of a string
function removeFirstLast(str) {
    return str.slice(1, -1);
}
  
// Driver code
const str = 'GeeksforGeeks';
  
console.log(removeFirstLast(str));


Output

eeksforGeek

Using String substring() Method

The string.substring() method returns the part of a given string from the start index to the end index. Indexing always start from zero (0).

Syntax:

string.substring(Startindex, Endindex)

Example: In this example, we will remove the first and the last character of the string using the substring() method in JavaScript.

Javascript




// JavaScript Program to remoove first 
// and last character of a string
function removeFirstLast(str) {
    return str.substring(1, str.length - 1);
}
  
// Driver code
const str = 'GeeksforGeeks';
  
console.log(removeFirstLast(str));


Output

eeksforGeek

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads