Skip to content

JavaScript trim last character | Example code

  • by

Use the slice() method to trim the last character in JavaScript. The slice syntax is much clearer and takes two arguments: the start index and the end index.

str.slice(0, -1); 
// equal to 
str.slice(0, str.length - 1); 

Positive is relative to the beginning, negative numbers are relative to the end. However other methods available are substring() and replace().

JavaScript trim last character

Simple example code slice() supports negative indexing, which means that slice(0, -1) is equivalent to slice(0, str.length - 1).

<!DOCTYPE html>

    let str = 'abc.ioF';
    var res = str.slice(0, -1)

    console.log("str before:",str)
    console.log("str after:",res)



JavaScript trim last character

Use the substring function:

let str = "12345.00";
str = str.substring(0, str.length - 1);
console.log(str); // 

With replace(), you can specify if the last character should be removed depending on what it is with a regular expression. For example, remove the last character only if the last character is a number.

  let str = 'abc.io0';
  // If the last character is not a number, it will not replace.
  var res =str.replace(/\d$/, '');

Do comment if you have any doubts or suggestions on this Js character topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *