In this tutorial, you will learn about how to remove the first and last character from a string in JavaScript.
In Javascript we can use the slice() and substring() method to remove first and last character from string.
1. Using slice method
To remove the first and last character from a string, we just need to specify the two arguments in slice method which are startIndex and endIndex.
- start index – the index (zero-based) at which we start extraction
- end index – extract characters up to, but not including this index. A negative index of
-1
means go up to, but not including the last character of the string
const str = 'hello';
const newStr = str.slice(1, -1);
console.log(newStr); // ell
2. Using substring method
The substring() method also works similar like slice method but in substring negative indexes are treated as 0 so that we need to use str.length-1 to get the endIndex.
const str = 'hello';
const newStr = str.substring(1,str.length-1);
console.log(newStr); // ell
The first parameter it takes is the start index (zero-based) and the second is the end index (up to, but not including).
3. Using both slice and substring method
Now we are chaining the both slice() and substring() methods to remove the first and last character from a string.
const str = 'hello';
const newStr = str.substring(1).slice(0,-1)
console.log(newStr); // ell
In the above code, we first remove the first character from a string using substring() method then we chain it to slice() method to remove the last character.
4. Using replace method
The replace method takes two arguments, the first argument is a regular expression and the second argument is replacement.
const str = '/hello/';
const newStr = str.replace(/^(.)|(.)$/g,'')
console.log(newStr); // hello