Before you make another step, remember, that strings in JavaScript are immutable. This means that you can’t alter the string by removing something from it.

So, when you want to remove the last n symbols from a string in JS, your only option is to create a new string that wouldn’t have these n characters.

This task is very similar to removing the last character from a JavaScript string.

Remove last n characters from a string with slice

The slice function is a convenient way to remove the last n characters from a JavaScript string. It accepts 2 parameters. The first one is the starting point. The second one is the number of items to remove from a string. We set it to the negative value to start the removal from the end of the string.

const text = 'string';
const n = 3;

const shortenedString = text.slice(0, -n);

Remove last n characters from a string with substring

You can use the built-in string function substring to get a string without the last n characters.

const text = 'string';
const n = 3;

const shortenedString = text.substring(0, text.length - n);

Keep in mind that the original string doesn’t change no matter what you try to do with it.

console.log(text); // string
console.log(shortenedString); // str