Use the slice() method to remove the last character from the string JavaScript. You must pass two arguments: the start and end indexes.
str.slice(0, -1)
Use slice(0, -1)
, it is equivalent to slice(0, str.length - 1)
.
Remove last character JavaScript
Simple example code.
<!DOCTYPE html>
<html lang="en">
<body>
<script>
let str = "12345.00";
console.log(str);
var res = str.slice(0, -1);
console.log(res);
</script>
</body>
</html>
Output:
Alternative Methods
Other methods available are substring()
and replace()
. substring()
does not have negative indexing, so be sure to use str.length - 1
when removing the last character from the string.
let str = 'abc.com';
str.substring(0, str.length - 1); // acb.co
str.substr(0, str.length - 1); // abc.co
replace()
takes either a string or a regular expression as its pattern
argument.
let str = 'abc.com';
str.replace(/.$/, ''); // abc.co
Remove the last character only if the last character is a number. You can use .replace(/\d$/, '')
as shown below.
let str = 'abc.io0';
str.replace(/\d$/, ''); // abc.io
Do comment if you have any doubts or suggestions on this Js remove char topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version