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>
<html>
<body>
<script>
let str = 'abc.ioF';
var res = str.slice(0, -1)
console.log("str before:",str)
console.log("str after:",res)
</script>
</body>
</html>
Output:
Use the substring function:
let str = "12345.00";
str = str.substring(0, str.length - 1);
console.log(str); //
12345.0
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.
<script>
let str = 'abc.io0';
// If the last character is not a number, it will not replace.
var res =str.replace(/\d$/, '');
console.log(res)// abc.io
</script>
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