Avatar ·

How to remove the last character from a string in JavaScript? (slice, substring, trim)

Hello everyone! I just started learning JavaScript and came across a seemingly simple task. I have a string, for example:

\n\n
let str = "Hello, world!";\n
\n\n

I need to remove the last character (the exclamation mark) from it, so that it becomes "Hello, world". I tried several methods, but nothing works as I expected.

\n\n

First, I tried str.trim(), but it only removes whitespace from the beginning and end of the string, not the last character. Then I wrote this code:

\n\n
str = str.slice(0, -1);\nconsole.log(str); // "Hello, world" – it worked!\n
\n\n

But I don't quite understand why this works. Why does -1 mean "the last character"? And are there other ways to do the same thing? For example,