Trim the Last N Characters from a String in JavaScript


JavaScript has quite a few methods to manipulate strings. One of those methods involves trimming the last N characters from a string. This Byte will show you two ways to achieve this: using the String.substring() method and conditionally removing the last N characters.

Using String.substring() to Trim Characters

The String.substring() method returns a new string that starts from a specified index and ends before a second specified index. We can use this method to trim the last N characters from a string. Let's see how this works with a simple example:

let str = "Hello, World!";
let trimmedStr = str.substring(0, str.length - 5);

In this code, str.length - 5 is used to calculate the ending index for the substring. This will output:

Hello, Wo

As you can see, the last 5 characters of the string have been removed.

Conditional Removal of Last N Characters

Sometimes, you might want to conditionally remove the last N characters from a string. This could be useful when you want to trim characters only when certain conditions are met. For instance, you might want to remove the last character from a string only if it is a comma.

One way to do this is with an if statement:

let str = "Hello, World!,";
if (str.endsWith(",")) {
    str = str.substring(0, str.length - 1);
Get free courses, guided projects, and more

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

In the above code, we used the String.endsWith() method to check if the string ends with a comma. If it does, we remove the last character. This isn't much different than our first example, except that it's surrounded by a conditional.

This will output:

Hello, World!

Note: Remember that String.substring() does not modify the original string. Instead, it returns a new string. This is because strings in JavaScript are immutable.

Another way to do it conditionally is with a regex string and the replace() method:

let str = "Hello, World!,";
let regex = /,$/g;
str = str.replace(regex, '');

console.log(str); // Hello, World!

This will only remove the comma at the end of the string if it is present.


In this Byte, we explored two ways to remove the last N characters from a string in JavaScript. We learned how to use the String.substring() method, and we also looked at how to conditionally remove characters.

Last Updated: August 21st, 2023
Was this helpful?

© 2013-2024 Stack Abuse. All rights reserved.