How to delete the last character of a string with JavaScript?

Sometimes, we want to delete the last character of a string with JavaScript.

In this article, we’ll look at how to delete the last character of a string with JavaScript.

How to delete the last character of a string with JavaScript?

To delete the last character of a string with JavaScript, we can use the string’s replace method.

For instance, we write:

const s = 'foobar'
const newS = s.replace(/(s+)?.$/, '')
console.log(newS)

to call s.replace with a regex that matches the last character from the string s and replace that with an empty string.

s matches whitespaces, and . matches any character.

The $ means the end of the string.

As a result, newS is 'fooba'.

Conclusion

To delete the last character of a string with JavaScript, we can use the string’s replace method.