JavaScript strings are immutable. This means that once the string was created it can’t be changed. When you need to remove the last character from a string in JavaScript, you should create a new string without this character.
How to delete last symbol in JS string using slice
const base = 'javascript, remove last char!'
const s = base.slice(0, -1);
console.log(s); // javascript, remove last char
The function slice
returns a part of the string. We pass in two values, start
and end
. Eventually slice
returns us a substring of base
between start
and end
.
If end
is a negative number, the lookup begins from the end of the string.
The statement
base.slice(0, -1);
Is the same as
base.slice(0, base.length - 1);
Use substring
to remove the last element from a string in JS
As the function slice
only returns us a substring and doesn’t mutate the original string, we can use the function substring
to get the same outcome.
const base = 'javascript, remove last char!'
const s = base.substring(0, base.length - 1);
console.log(s); // javascript, remove last char
Take a note, though, that if you pass a negative number into substring
as a second argument, you’ll get an empty string
base.substring(0, -1); // ''
The behavior is different from slice
with regards to negative indicies.
Conclusion
Key points:
- It’s impossible to chang strings in JavaScript after initialization
- If you need to delete the last char of the string in JS, you should create a new string
- You can use either
slice
orsubstring
Read more JavaScript tutorials or Learn Full-Stack JS from scratch!