3 Ways to Remove Last Character from String in JavaScript

There are the following methods to remove a last character from a string in JavaScript.

  1. Method 1: Using the string.slice() function
  2. Method 2: Using the string.substring() function
  3. Method 3: Using the string.replace() function

Method 1: Using the string.slice() function

To remove the last character from a string in JavaScript, you can use the string.slice() method and pass the first argument 0 and second argument -1. The slice() is a built-in string method that extracts a part of a string and returns the extracted part in a new string. The slice() method takes two arguments: the start and end indexes.

Example

const data = "houseofthedragon"
const modifiedData = data.slice(0, -1)
console.log(modifiedData)
console.log(data)

Output

houseofthedrago
houseofthedragon

You can see that using the slice() method, we removed the last character of the main string “houseofthedragon” and the output string “houseofthedrago”. In addition, the character “n” is removed since it is the last character of the string.

Method 2: Using the substring() method

The substring() is a built-in JavaScript method that extracts a part of a string. The substring() method does not support a negative index like the slice() method. o, we can pass the string.length-1 argument to the substring() function to remove the last character from a string.

Example

const data = "houseofthedragon"
const modifiedData = data.substring(0, data.length - 1)
console.log(modifiedData)
console.log(data)

Output

houseofthedrago
houseofthedragon

You can see that by using the substring() method, we removed the last character of a string.

Method 3: Using the string.replace() function

To remove the last character from a string using regular expressions and replace() method, use the replace(/.$/, ”) function that replaces the last character of the string with an empty string.

The string.replace() is a built-in JavaScript method that searches a string for a value or a regular expression. For example, we. We can use the replace() method to remove the last character of a string.

const data = "houseofthedragon"
const modifiedData = data.replace(/.$/, '');
console.log(modifiedData)
console.log(data)

Output

houseofthedrago
houseofthedragon

Using replace() and regex, we replace the last character “n” with an empty string, which means we successfully removed the last character from a string.

Conclusion

The easiest way to remove the last character of a string is using a string.slice() method in JavaScript.

Related posts

How to remove a character from a string

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.