JavaScript Program to Remove First and Last Characters from a String
Last Updated :
13 Sep, 2023
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
function removeFirstLast(str) {
return str.slice(1, -1);
}
const str = 'GeeksforGeeks' ;
console.log(removeFirstLast(str));
|
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
function removeFirstLast(str) {
return str.substring(1, str.length - 1);
}
const str = 'GeeksforGeeks' ;
console.log(removeFirstLast(str));
|
Share your thoughts in the comments
Please Login to comment...