You are currently viewing 4 Ways to Remove first and last Character from String in JavaScript

4 Ways to Remove first and last Character from String in JavaScript

Remove first and last Character from String JavaScript

In this article, we will discuss how to remove first and last character from a string in Javascript. Let’s look at some ways:

Using substring() method:

We need to use the ‘substring()’ method to remove the first and last characters. The substring() method is a built-in method in JavaScript strings that returns a portion of the string between two indexes. If we pass two indexes of string as a parameter, it will return portion of the string between two indexes. So we have to pass (1) to remove the first character and (str.length – 1) to remove the last character of the string.

It doesn’t modify the original string but returns a new string that represents the extracted portion of the original string.

const str = "JavaScript";
const newStr = str.substring(1, str.length - 1);
console.log(newStr);

// Output : avaScrip

Using slice() method:

This method is similar to substring() method. It also returns the portion of the string between the two indexes, i.e. the parameter of the function slice(). We can also pass negative value index, like -1, -2, etc. If we pass a negative index (-1), it specifies the string’s last character. So in this case we have to pass (1) to remove the first character and (- 1) to remove the last character of the string.

const str = "JavaScript";
const newStr = str.slice(1, -1);
console.log(newStr);

// Output : avaScrip

Using substr() method:

It uses a different syntax. We should pass two arguments instead of specifying two indexes. It returns new string that represents the extracted portion of the original string. So we have to pass the starting index (1) and the length of the substring (str.length – 2).

const str = "JavaScript";
const newStr = str.substr(1, str.length - 2);
console.log(newStr);

// Output : avaScrip

Using split() method and join() method:

In this method, we’re going to do three things:

  1. first split the original string into an array of individual characters using using split(‘ ‘),
  2. second remove the first and last characters of the array using slice() method and
  3. Finally, join(”) to join the remaining characters back into a string.
const str = "JavaScript";
const newStr = str.split('').slice(1, -1).join('');
console.log(newStr);

// Output : avaScrip

 

READ ALSO  3 Easy Ways to Get Multi-Selected Options in JavaScript

All of these approaches are valid and achieve the same result: removing the first and last character from the string and returning the remaining substring. We can also remove first character from string using similar ways.

Leave a Reply